package xcmg.device.service.purchase;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import xcmg.device.dao.entity.DataDictionaryDO;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.agentPlan.AgentPlanDO;
import xcmg.device.dao.entity.basic.MaterialsPurchaseInfo;
import xcmg.device.dao.entity.basic.MaterialsSupplierDO;
import xcmg.device.dao.entity.basic.SystemParameter;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.entity.marketing.MarketingActivityDO;
import xcmg.device.dao.entity.purchase.BillStockDO;
import xcmg.device.dao.entity.purchase.BuyPlanDO;
import xcmg.device.dao.entity.purchase.BuyPlanDetailDO;
import xcmg.device.dao.entity.purchase.PurchaseGroupDO;
import xcmg.device.dao.entity.purchase.PurchaseInboundDO;
import xcmg.device.dao.entity.purchase.PurchaseInboundDetailDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestCrmDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDetailCrmDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDetailDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestLogDO;
import xcmg.device.dao.entity.sale.SaleIntentionDO;
import xcmg.device.dao.entity.sale.SaleIntentionDetailDO;
import xcmg.device.dao.entity.taskRecord.TaskRecordDO;
import xcmg.device.dao.mapper.BuyPlanDetailMapper;
import xcmg.device.dao.mapper.BuyPlanMapper;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.dao.mapper.DataDictionaryMapper;
import xcmg.device.dao.mapper.MarketingMaterialsMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.ProfileMapper;
import xcmg.device.dao.mapper.PurchaseGroupMapper;
import xcmg.device.dao.mapper.PurchaseInboundDetailMapper;
import xcmg.device.dao.mapper.PurchaseInboundMapper;
import xcmg.device.dao.mapper.PurchaseRequestDetailMapper;
import xcmg.device.dao.mapper.PurchaseRequestLogMapper;
import xcmg.device.dao.mapper.PurchaseRequestMapper;
import xcmg.device.dao.mapper.SaleIntentionDetailMapper;
import xcmg.device.dao.mapper.SaleIntentionMapper;
import xcmg.device.dao.mapper.agentPlan.AgentPlanMapper;
import xcmg.device.dao.mapper.basic.MaterialsSupplierMapper;
import xcmg.device.dao.mapper.taskRecord.TaskRecordMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.DateUtil;
import xcmg.device.infra.EasyExcelUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExcelUtil;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.infra.ImportUtil;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.infra.enums.PurchaseRequestBillStatusEnum;
import xcmg.device.infra.enums.PurchaseStatus;
import xcmg.device.infra.enums.PurchaseType;
import xcmg.device.infra.enums.TaskRecordEnum;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.basic.DataDictionaryService;
import xcmg.device.service.basic.MaterialsService;
import xcmg.device.service.basic.SystemParameterService;
import xcmg.device.service.company.CompanyDealerService;
import xcmg.device.service.company.CompanyInfoService;
import xcmg.device.service.marketing.MarketingActivityService;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.basic.DataDictionaryVO;
import xcmg.device.service.vo.basic.MaterialsVO;
import xcmg.device.service.vo.company.CompanyInfoVO;
import xcmg.device.service.vo.marketing.MarketingActivityPriceVO;
import xcmg.device.service.vo.marketing.MarketingMaterialsVO;
import xcmg.device.service.vo.purchase.PurchaseMaterialsShowVO;
import xcmg.device.service.vo.purchase.PurchaseReqeustReportVO;
import xcmg.device.service.vo.purchase.PurchaseRequestDetailVO;
import xcmg.device.service.vo.purchase.PurchaseRequestExternalVO;
import xcmg.device.service.vo.purchase.PurchaseRequestReportParamVO;
import xcmg.device.service.vo.purchase.PurchaseRequestVO;
import xcmg.device.service.vo.purchase.TimelinessReportParamVO;
import xcmg.device.service.vo.purchase.TimelinessReportVO;
import xcmg.device.service.vo.purchase.exportPurchaseVO;
import xcmg.device.service.vo.shell.MaterialsDetail;
import xcmg.device.service.vo.shell.PurOrderParams;
import xcmg.device.service.vo.warehouse.app.EnableAndOccupyVO;
import xcmg.device.service.warehouse.CommonService;
import xcmg.device.service.warehouse.WarehouseInventoryService;
import xcmg.device.util.CompanyUtil;
import xcmg.device.util.DecimalUtil;
import yb.ecp.fast.dto.UserCacheDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static xcmg.device.service.vo.purchase.PurchaseRequestExternalVO.SOURCE_CRM;
import static xcmg.device.service.vo.purchase.PurchaseRequestExternalVO.SOURCE_E_COMMERCE;
import static xcmg.device.service.vo.purchase.PurchaseRequestExternalVO.SOURCE_GSS;
import static xcmg.device.service.vo.purchase.PurchaseRequestExternalVO.SOURCE_JCK;

/**
 * Created by sqq on 2018/1/2.
 */
@Service
@Slf4j
public class PurchaseRequestService {

    @Autowired
    private PurchaseRequestMapper purchaseRequestMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private PurchaseRequestDetailMapper purchaseRequestDetailMapper;

    @Autowired
    private MaterialsService materialsService;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private DataDictionaryMapper dataDictionaryMapper;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private MarketingActivityService marketingActivityService;


    @Autowired
    private WarehouseInventoryService warehouseInventoryService;

    @Autowired
    private PurchaseInboundDetailMapper purchaseInboundDetailMapper;

    @Autowired
    private PurchaseGroupMapper purchaseGroupMapper;

    @Autowired
    private CompanySupplierMapper companySupplierMapper;

    @Autowired
    private PriMaterialsMapper priMaterialsMapper;

    @Autowired
    private BuyPlanMapper buyPlanMapper;

    @Autowired
    private BuyPlanDetailMapper buyPlanDetailMapper;

    @Autowired
    private PurchaseRequestLogMapper purchaseRequestLogMapper;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private PurchaseInboundMapper purchaseInboundMapper;

    @Autowired
    private SaleIntentionMapper saleIntentionMapper;

    @Autowired
    private MaterialsSupplierMapper materialsSupplierMapper;

    @Autowired
    private SystemParameterService systemParameterService;

    @Autowired
    private CompanyDealerService companyDealerService;
    @Autowired
    private SaleIntentionDetailMapper saleIntentionDetailMapper;

    @Autowired
    private AgentPlanMapper agentPlanMapper;

    @Autowired
    MaterialsPurchaseInfoService materialsPurchaseInfoService;

    @Autowired
    private MarketingMaterialsMapper marketingMaterialsMapper;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private CompanyUtil companyUtil;

    @Autowired
    private TaskRecordMapper taskRecordMapper;

    @Autowired
    private ProfileMapper profileMapper;
//    @Value("${erp.syncFlag}")
//    private String syncFlag;
//
//    @Value("${baidu.trans.appid}")
//    private String appid;
//
//    @Value("${baidu.trans.securityKey}")
//    private String securityKey;

    private static final Logger logger = LoggerFactory.getLogger(PurchaseRequestService.class);

    @Value("${spring.file.download.path}")
    private String filePath;
    private String templateExcelFileName = "DlsCgSqMb.xls";

    private String replaceTemplateExcelFileName = "ReplaceDlsCgSqMb.xls";

    /**
     * 入库状态：0未入库
     */
    private static final Integer INBOUND_STATUS_NO = 0;

    /**
     * 按照发运交接单展示的公司
     */
    private static final String SHOW_BY_DELIVERY_RECEIPT = "SHOW_BY_DELIVERY_RECEIPT";


    //非直投只查询自己的零件信息的过滤配置
    private static final String SELF_MATERIAL_FILTER = "SELF_MATERIAL_FILTER";


    /**
     * 是否按照发运交接单展示。0否1是
     */
    private static final String SHOW_BY_RECEIPT_YES = "1", SHOW_BY_RECEIPT_NO = "0";

    /**
     * 是否加价：0否，1是
     */
    private static final Short IS_RAISE_YES = 1;


    /**
     * 是否生成采购订单。0否1是
     */
    private static final Short GEN_ORDER_FLAG_NO = 0;

    private static final String GSS_USER_ID = "gss_user";
    private static final String GSS_AGENT_ID = "gss_agent";


    public PageCommonVO list(SearchCommonVO<PurchaseRequestVO> condition, String orgId) {
        PurchaseRequestVO filters = condition.getFilters();
        List<String> billNos = xcmg.device.infra.StringUtil.getStrSplitList(filters.getBillNo());
        if (CollectionUtils.isNotEmpty(billNos) && billNos.size() > 1) {
            filters.setBillNos4Inboud(billNos);
        }

        filters.setBillNosList(xcmg.device.infra.StringUtil.splitList(filters.getBillNos()));
        String purchaseNames = condition.getFilters().getPurchaseNames();
        if (!StringUtils.isEmpty(purchaseNames)) {
            List<String> purchaseNamesList;
            String supplierOrgId = filters.getSupplierOrgId();
            if (StringUtils.isEmpty(supplierOrgId)) {//说明是售卖方查询
                purchaseNamesList = companyDealerService.listFullNamesByShortName(supplierOrgId, purchaseNames);
            } else {
                purchaseNamesList = companyDealerService.listFullNamesByShortName(null, purchaseNames);
            }
            if (CollectionUtils.isNotEmpty(purchaseNamesList)) {
                filters.setPurchaseNamesList(purchaseNamesList);
            } else {
                PageCommonVO pageCommonVO = new PageCommonVO();
                pageCommonVO.setPageInfo(new PageInfo(Collections.EMPTY_LIST));
                pageCommonVO.setPageInfoList(Collections.EMPTY_LIST);
                return pageCommonVO;
            }
        }

        filters = resetVoucherNos(filters);

        PageCommonVO pageCommonVO = new PageCommonVO();
        List<PurchaseRequestDO> doList = null;
        if (filters.getSeller()) {
            PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
            doList = purchaseRequestMapper.listByStatus(filters);
        } else {
            if (StringUtils.isEmpty(condition.getSort())) {
                condition.setSort("create_date desc");
            }
            PageHelperPlus.orderBy(condition.getSort());
            PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
            doList = purchaseRequestMapper.list(filters);
        }
        List<String> billNoList = new ArrayList<>();
        List<PurchaseRequestVO> voList = new ArrayList<>();
        for (PurchaseRequestDO purchaseRequestDO : doList) {
            if (purchaseRequestDO == null) {
                continue;
            }
            billNoList.add(purchaseRequestDO.getBillNo());
            purchaseRequestDO.setTotalValue(purchaseRequestDO.getTotalValue().divide(new BigDecimal("100")));
            purchaseRequestDO.setSettlementValue(purchaseRequestDO.getSettlementValue().divide(new BigDecimal("100")));

            if (!filters.getSeller()) {
                purchaseRequestDO.setPlatCompany(companyInfoMapper.item(purchaseRequestDO.getSupplierOrgId()) != null);
            }
            PurchaseRequestVO purchaseRequestVO = getVO(purchaseRequestDO, orgId);

            if (!filters.getSeller()) {
                convertStockInfo(purchaseRequestVO);
            }

            voList.add(purchaseRequestVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    private void convertStockInfo(PurchaseRequestVO purchaseRequestVO) {
        List<BillStockDO> billStockDOs = getStockInfo(purchaseRequestVO.getIsDirectCast(), purchaseRequestVO.getSoldOrgId(), purchaseRequestVO.getBillNo());
        if (CollectionUtils.isNotEmpty(billStockDOs)) {
            purchaseRequestVO.setStockFlag(1);
        } else {
            purchaseRequestVO.setStockFlag(0);
        }
    }

    private List<BillStockDO> getStockInfo(Integer directCast, String soldOrgId, String billNo) {
        String ynOrgId = companyUtil.ynOrgId();
        List<BillStockDO> billStockDOs = new ArrayList<BillStockDO>();
        if (Integer.valueOf(1).equals(directCast)) {
            if (ynOrgId.equals(soldOrgId)) {
                String orderNo = purchaseRequestMapper.getBillNoBySourceNo(billNo);
                if (StringUtils.isEmpty(orderNo)) {
                    orderNo = billNo;
                }
                billStockDOs = purchaseRequestMapper.selectStockInfoByBillNo(orderNo);
            }
        } else {
            if (ynOrgId.equals(soldOrgId)) {
                billStockDOs = purchaseRequestMapper.selectStockInfoByBillNo(billNo);
            }
        }
        return billStockDOs;
    }

    /**
     * @Des 采购订单报表
     * @Date 2020/10/28 18:24
     * @Author wangzhaoyu
     * @Param [requestVO]
     * @Return void
     */
    public PageCommonVO purchaseRequestReport(SearchCommonVO<PurchaseRequestReportParamVO> condition) {

        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        PurchaseRequestReportParamVO filters = condition.getFilters();
        List<PurchaseReqeustReportVO> purchaseReqeustReports = purchaseRequestDetailMapper.purchaseRequestReport(filters);
        PageCommonVO result = new PageCommonVO();
        result.setPageInfo(new PageInfo(purchaseReqeustReports));
        result.setPageInfoList(purchaseReqeustReports);
        return result;
    }

    /**
     * @Des 采购报表导出
     * @Date 2020/10/29 10:59
     * @Author wangzhaoyu
     * @Param [paramVO]
     * @Return void
     */
    public void purchaseRequestReportExport(PurchaseRequestReportParamVO paramVO) throws Exception {
        List<PurchaseReqeustReportVO> purchaseReqeustReports = purchaseRequestDetailMapper.purchaseRequestReport(paramVO);
        purchaseRequestReportExport(purchaseReqeustReports);
    }

    public void purchaseRequestReportExport(List<PurchaseReqeustReportVO> purchaseReqeustReports) throws Exception {
        String title = "采购报表导出";
        String[] rowsName = new String[]{"序号", "采购计划单号", "零件号", "零件名称", "计划员", "计划下达时间", "采购订单号", "采购员", "采购下单时间",
                "采购入库时间"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs;
        int number = 0;//序号
        for (int i = 0; i < purchaseReqeustReports.size(); i++) {
            PurchaseReqeustReportVO e = purchaseReqeustReports.get(i);
            objs = new Object[rowsName.length];
            objs[0] = number + 1;
            objs[1] = e.getBuyPlanOrder();
            objs[2] = e.getMaterialsNo();
            objs[3] = e.getMaterialsDes();
            objs[4] = e.getBuyPlanCreateName();
            objs[5] = e.getBuyPlanCreateDate() == null ? "" : DateUtil.formatDateTime(e.getBuyPlanCreateDate());
            objs[6] = e.getBillNo();
            objs[7] = e.getPurchaseRequestCreateName();
            objs[8] = e.getPurchaseRequestCreateDate() == null ? "" : DateUtil.formatDateTime(e.getPurchaseRequestCreateDate());
            objs[9] = e.getAllInboundTime() == null ? "" : DateUtil.formatDateTime(e.getAllInboundTime());
            dataList.add(objs);
            number++;
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    /**
     * 兼容多个采购凭证搜索的情况
     *
     * @param filter
     * @return
     */
    private PurchaseRequestVO resetVoucherNos(PurchaseRequestVO filter) {
        if (StringUtils.isNotBlank(filter.getVoucherNo())) {
            List<String> voucherNoList = xcmg.device.infra.StringUtil.getStrSplitList(filter.getVoucherNo());
            if (voucherNoList.size() > 1) {
                filter.setVoucherNoList(voucherNoList);
                filter.setVoucherNo(null);
            }
        }
        return filter;
    }

    /**
     * @Author: WangKe
     * @Description: 根据采购计划生成采购单，不同供应商生成不同采购单
     * @Date: 2018/12/26 0026
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode insertByBuyPlan(PurchaseRequestVO purchaseRequestVO, String orgId) throws Exception {
        if (CollectionUtils.isEmpty(purchaseRequestVO.getMaterialsList())) {
            return ErrorCode.IllegalArument;
        }
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
        if (companyInfoDO == null) {
            return ErrorCode.IllegalArument;
        }
        purchaseRequestVO.setPurchaseOrgId(orgId);
        purchaseRequestVO.setPurchaseOrgName(companyInfoDO.getCompanyName());
        Map<String, List<PurchaseRequestDetailVO>> map = new HashMap<>(64);
        for (PurchaseRequestDetailVO detailVO : purchaseRequestVO.getMaterialsList()) {
            if (map.containsKey(detailVO.getSupplierCode())) {
                map.get(detailVO.getSupplierCode()).add(detailVO);
            } else {
                List<PurchaseRequestDetailVO> list = new ArrayList<>();
                list.add(detailVO);
                map.put(detailVO.getSupplierCode(), list);
            }
        }
        for (Map.Entry<String, List<PurchaseRequestDetailVO>> entry : map.entrySet()) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemByCode(orgId, entry.getKey());
            if (supplierDO == null) {
                throw new Exception("供应商不存在：" + entry.getValue().get(0).getSupplierCode());
            }
            String supplierOrgId;
            String platOrgId = supplierDO.getPlatOrgId();
            if (StringUtils.isNotEmpty(platOrgId)) {
                supplierOrgId = platOrgId;
            } else {
                supplierOrgId = supplierDO.getSupplierOrgId();
            }
            purchaseRequestVO.setSupplierOrgId(supplierOrgId);
            purchaseRequestVO.setSupplierOrgName(supplierDO.getCompanyName());
            purchaseRequestVO.setMaterialsList(entry.getValue());
            this.insert(purchaseRequestVO, orgId, null, null);
        }
        return ErrorCode.Success;
    }

    private String getCompanyType(Integer directType, String sellOrgId) throws Exception {
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(sellOrgId);
        if (companyInfoDO == null) {
            throw new Exception("销售单位不存在");
        }
        if (Integer.valueOf(1).equals(directType)) {
            if (String.valueOf(1).equals(companyInfoDO.getCompanyType())) {
                return String.valueOf(1);
            } else {
                return String.valueOf(2);
            }
        } else {
            return String.valueOf(3);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode insert(PurchaseRequestVO purchaseRequestVORegion, String orgId, String operate, String sourceType) throws Exception {
        if (null == purchaseRequestVORegion.getSelfMade()) {
            purchaseRequestVORegion.setSelfMade(0);
        }
        if (!(0 == purchaseRequestVORegion.getSelfMade() || 1 == purchaseRequestVORegion.getSelfMade()
                || 2 == purchaseRequestVORegion.getSelfMade())) {
            throw new CommonBusiExceptions("参数错误，自制类型错误！");
        }


        PurchaseRequestVO purchaseRequestVO = new PurchaseRequestVO();
        BeanUtils.copyProperties(purchaseRequestVORegion, purchaseRequestVO);
        //如果是直投校验零件是否为所选供应商下的零件
        checkMaterialExist(purchaseRequestVO, orgId, operate);

        purchaseRequestVO.setCreateDate(new Date());
        purchaseRequestVO.setSubmitDate(new Date());
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            return ErrorCode.IllegalArument;
        }
        if (!purchaseRequestVO.getSeller() && PurchaseStatus.WaitAudit.toString().equals(purchaseRequestVO.getBillStatus())) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(purchaseRequestVO.getPurchaseOrgId(), purchaseRequestVO.getSupplierOrgId());
            if (supplierDO == null) {
                return ErrorCode.IllegalArument;
            }
            //如果供应商不是平台企业直接置为审核通过
            if (!supplierDO.getIsPlatCompany()) {
                purchaseRequestVO.setBillStatus(PurchaseStatus.AuditPass.toString());
            }
        }
        String billId = textResult.getValue();
        purchaseRequestVO.setBillId(billId);
        String type = getCompanyType(purchaseRequestVO.getIsDirectCast(), purchaseRequestVO.getSoldOrgId());
        if ("auto".equals(sourceType)) {
            purchaseRequestVO.setBillNo(purchaseRequestVO.getBillNo() + "Z");
        } else {
            String companyOrgId = null;
            if ("1".equals(type)) {
                companyOrgId = purchaseRequestVO.getSupplierOrgId();
            } else {
                companyOrgId = orgId;
            }
            String no = genDocumentService.getPurchaseDocumentNo(type, companyOrgId, purchaseRequestVORegion.getSelfMade(),
                    purchaseRequestVORegion.getIsDirectCast());
            purchaseRequestVO.setBillNo(no);
        }

        purchaseRequestVO.setDel(false);
        purchaseRequestVO.setUpdateDate(new Date());
        if (StringUtil.isNullOrEmpty(purchaseRequestVO.getDirectSourceOrder()) && StringUtil.isNullOrEmpty(purchaseRequestVO.getDeliveryOrgId())) {
            purchaseRequestVO.setDeliveryOrgId(purchaseRequestVO.getPurchaseOrgId());
            purchaseRequestVO.setDeliveryOrgName(purchaseRequestVO.getPurchaseOrgName());
        }
        if (!StringUtil.isNullOrEmpty(purchaseRequestVO.getDeliveryOrgId()) && StringUtil.isNullOrEmpty(purchaseRequestVO.getDeliveryOrgName())) {
            CompanyInfoDO companyInfoDO = companyInfoMapper.item(purchaseRequestVO.getDeliveryOrgId());
            if (companyInfoDO != null) {
                purchaseRequestVO.setDeliveryOrgName(companyInfoDO.getCompanyName());
            }
        }
        if (StringUtil.isNullOrEmpty(purchaseRequestVO.getDirectSourceOrder()) && StringUtil.isNullOrEmpty(purchaseRequestVO.getSoldOrgId())) {
            purchaseRequestVO.setSoldOrgId(purchaseRequestVO.getSupplierOrgId());
            purchaseRequestVO.setSoldOrgName(purchaseRequestVO.getSupplierOrgName());
        }
        if (StringUtil.isNullOrEmpty(purchaseRequestVO.getDirectSourceOrder())) {
            if (StringUtil.isNullOrEmpty(purchaseRequestVO.getDrawerOrgId())) {
                purchaseRequestVO.setDrawerOrgId(purchaseRequestVO.getSupplierOrgId());
                purchaseRequestVO.setDrawerOrgName(purchaseRequestVO.getSupplierOrgName());
            }
        } else {
            purchaseRequestVO.setDrawerOrgId(purchaseRequestVO.getSoldOrgId());
            purchaseRequestVO.setDrawerOrgName(purchaseRequestVO.getSoldOrgName());
        }
        DataDictionaryDO auditDataDictionaryDO = dataDictionaryMapper.itemByCode(PurchaseStatus.Name.toString(), purchaseRequestVO.getBillStatus());
        if (auditDataDictionaryDO != null) {
            purchaseRequestVO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        DataDictionaryDO typeDataDictionaryDO = dataDictionaryMapper.itemByCode("CGJB", purchaseRequestVO.getPurchaseType());
        if (typeDataDictionaryDO != null) {
            purchaseRequestVO.setTypeDesc(typeDataDictionaryDO.getName());
        }
        if (purchaseRequestVO.getSeller()) {
            purchaseRequestVO.setSupplierOrgName(getCompanyName(purchaseRequestVO.getSupplierOrgId()));
        } else {
            purchaseRequestVO.setPurchaseOrgName(getCompanyName(purchaseRequestVO.getPurchaseOrgId()));
        }
        ActionResult userAuth = authClient.getUserDetail(purchaseRequestVO.getCreateId());
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        if (userInfo != null) {
            purchaseRequestVO.setCreateName(userInfo.getName());
            purchaseRequestVO.setUpdateName(userInfo.getName());
        }

        PurchaseRequestDO purchaseRequestDO = getDO(purchaseRequestVO);
        ErrorCode code = ErrorCode.Success;
        List<PurchaseRequestDetailVO> detailList = purchaseRequestVO.getMaterialsList();
        BigDecimal totalValue = new BigDecimal("0");
        BigDecimal totalSourceValue = BigDecimal.ZERO;

        //查找采购计划详情
        BuyPlanDO buyPlanDO = buyPlanMapper.findByPlanOrder(purchaseRequestDO.getBuyPlanOrder(), purchaseRequestDO.getPurchaseOrgId());
        List<PurchaseRequestDetailDO> purchaseRequestDetailDOS = new ArrayList<>();
        BigDecimal totalQuantity = BigDecimal.ZERO;
        if (detailList != null && detailList.size() > 0) {
            for (PurchaseRequestDetailVO detail : detailList) {
                totalQuantity = totalQuantity.add(detail.getQty() == null ? BigDecimal.ZERO : detail.getQty());
                if (null == detail.getSettlementPrice()) {
                    throw new Exception("零件【" + detail.getMaterialsNo() + "】成交单价不能为空");
                }
                detail.setSettlementPrice(detail.getSettlementPrice().multiply(new BigDecimal("100")));
                if (null == detail.getPrice()) {//单价为空默认为0
                    detail.setPrice(BigDecimal.ZERO);
                } else {
                    detail.setPrice(detail.getPrice().multiply(new BigDecimal("100")));
                }
                BigDecimal qty = detail.getQty();
                BigDecimal amont = BigDecimal.valueOf(detail.getSettlementPrice().multiply(qty).doubleValue());
                totalValue = totalValue.add(amont);
                detail.setApplyTotalPrice(amont);
                detail.setBillId(billId);
                PurchaseRequestDetailDO purchaseRequestDetailDO = getDetailDO(detail);
                purchaseRequestDetailDO.setCustomMaterialsNo(priMaterialsMapper.findCustomMaterialsNo(detail.getMaterialsNo(), purchaseRequestDO.getSupplierOrgId()));
                //校验详情数据是否存在
                PurchaseRequestDetailDO requestDetailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(purchaseRequestDetailDO.getBillId(),
                        purchaseRequestDetailDO.getMaterialsNo(), purchaseRequestDetailDO.getRowNo());
                if (null != requestDetailDO) {
                    continue;
                }

                code = purchaseRequestDetailMapper.insert(purchaseRequestDetailDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
                if (code != ErrorCode.Success) {
                    return code;
                }
                purchaseRequestDetailDOS.add(purchaseRequestDetailDO);
                if (!StringUtil.isNullOrEmpty(purchaseRequestDO.getDirectSourceOrder())) {
                    BigDecimal totalPrice = detail.getSourcePrice().multiply(qty);
                    totalSourceValue = totalSourceValue.add(totalPrice);
                }

                //更新采购计划详情状态
                if (buyPlanDO != null) {
                    buyPlanDetailMapper.updateIsGenerate(buyPlanDO.getId(), purchaseRequestDetailDO.getMaterialsNo());
                }
            }
        }
        purchaseRequestDO.setSettlementValue(totalValue);
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setTotalQuantity(totalQuantity);
        purchaseRequestDO.setInboundEnable(1);

        //主机厂下直投单时，不能选择额度不够的代理商下的直投单
        if (!StringUtil.isNullOrEmpty(purchaseRequestDO.getDirectSourceOrder())) {
            CompanyInfoDO companyInfoDO = companyInfoMapper.item(purchaseRequestDO.getPurchaseOrgId());
            if (companyInfoDO != null && companyInfoDO.getIsSap() == 1) {
                CompanyDealerDO dealerDO = companyDealerMapper.itemByOrgId(purchaseRequestDO.getPurchaseOrgId(), purchaseRequestDO.getDeliveryOrgId());
                if (dealerDO == null) {
                    throw new Exception("未找到客户记录");
                }
                if (dealerDO.getEnableLimit() == 1) {
                    BigDecimal price = BigDecimal.ZERO;
                    if (totalSourceValue != null) {
                        price = totalSourceValue.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    }
                    BigDecimal totalPrice = dealerDO.getUsedLimit().add(price);
                    if (totalPrice.compareTo(dealerDO.getTotalLimit()) > 0) {
                        throw new Exception("客户额度已超额");
                    }
                }
            }
        }

        boolean isYn = commonService.checkIsYnOrgId(purchaseRequestDO.getSupplierOrgId());
        if (isYn) {
            if (StringUtils.isBlank(purchaseRequestVO.getSalesCode())) {
                throw new CommonBusiExceptions("销售组织代码为空，请清空浏览器缓存重试！");
            }
            if ((purchaseRequestDO.getBillNo().startsWith("Z") || purchaseRequestDO.getBillNo().startsWith("P")) &&
                    (StringUtils.isBlank(purchaseRequestDO.getSendCompanyCode()) || StringUtils.isBlank(purchaseRequestDO.getSendCompanyName()))) {
                throw new CommonBusiExceptions("参数异常，发货公司为空，请清空浏览器缓存重试！");
            }
        }

        code = purchaseRequestMapper.insert(purchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
        //如果是根据采购计划单新增，更新采购计划单状态
        if (code.getCode() == 0 && buyPlanDO != null) {
            //获取现在数据库中的采购计划详情，判断采购计划创建订单的状态
            List<BuyPlanDetailDO> list = buyPlanDetailMapper.list(buyPlanDO.getId());
//            int sendStatus = buyPlanDetailMapper.findSendStatus(buyPlanDO.getId());
            //需求：创建采购订单的时候如果所有未结单的零件都创建了采购订单则需要把采购计划的创建状态改为已创建（send_status=2）,如果部分创建则为部分创建
            //判断逻辑：1.如果创建了采购订单的零件行数+没有创建订单且接单的额零件行数=总行数（赋值全部创建）
            //2.否则如果创建了采购订单的零件行数为0则赋值为未创建
            //3.其他情况均为部分创建
            int allDetailNum = 0;//计划所有零件行数
            int generateNum = 0;//创建了采购订单的零件行数
            int noGeneManualFinish = 0;//没有创建订单且接单的额零件行数
            for (BuyPlanDetailDO detailDO : list) {
                allDetailNum++;
                Integer isGenerate = detailDO.getIsGenerate();
                String finishState = detailDO.getFinishState();
                if (isGenerate != null && isGenerate.equals(1)) {
                    generateNum++;
                } else if (!StringUtils.isEmpty(finishState) && "1".equals(finishState)) {
                    noGeneManualFinish++;
                }
            }
            Integer sendStatus = null;
            if (generateNum + noGeneManualFinish - allDetailNum == 0) {
                sendStatus = 2;
            } else if (generateNum == 0) {
                sendStatus = 0;
            } else {
                sendStatus = 1;
            }

            buyPlanMapper.updateSendStatus(purchaseRequestDO.getBuyPlanOrder(), sendStatus, purchaseRequestDO.getPurchaseOrgId());
        }
        if (purchaseRequestDO.getBillStatus().equals(PurchaseStatus.WaitAudit.toString())) {
            String userName = "";
            if (userInfo != null) {
                userName = userInfo.getName();
            }
            insetLog(userName, purchaseRequestDO.getCreateId(), "[提交订单]", purchaseRequestDO);
            // 生成壳牌订单，内部判断是否需要生成
//            genShellOrder(purchaseRequestDO, purchaseRequestDetailDOS);
        }

        if (code.getCode() == 0 && !StringUtil.isNullOrEmpty(purchaseRequestVO.getDirectSourceId())) {
            purchaseRequestMapper.updateDirectAddEnable(purchaseRequestVO.getDirectSourceId(), 1);
        }
        return code;
    }

    private void checkMaterialExist(PurchaseRequestVO purchaseRequestVO, String orgId, String operate) throws Exception {
        if (null != purchaseRequestVO.getSelfMade() &&
                !(1 == purchaseRequestVO.getSelfMade() || 0 == purchaseRequestVO.getSelfMade()
                        || 2 == purchaseRequestVO.getSelfMade())) {
            throw new Exception("自制类型不正确！");
        }

        //是否自制件  ：0-否，1-是自制件 2基础机
        boolean salfMade = null != purchaseRequestVO.getSelfMade() && 1 == purchaseRequestVO.getSelfMade();
        //是否基础机
        boolean baseMach = null != purchaseRequestVO.getSelfMade() && 2 == purchaseRequestVO.getSelfMade();
        String sendCompanyCode = purchaseRequestVO.getSendCompanyCode();

        CompanyInfoDO soldInfo = companyInfoMapper.item(purchaseRequestVO.getSoldOrgId());
        if ("1".equals(soldInfo.getCompanyType()) && Integer.valueOf(1).equals(purchaseRequestVO.getIsDirectCast())) {
            List<PurchaseRequestDetailVO> materialsList = purchaseRequestVO.getMaterialsList();
            for (PurchaseRequestDetailVO purchaseRequestDetailVO : materialsList) {
                String materialsNo = purchaseRequestDetailVO.getMaterialsNo();
                PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, purchaseRequestVO.getSoldOrgId());
                if (priMaterialsDO == null) {
                    throw new Exception("此零件不存在");
                }
            }
        } else {
            //是否直投
            Integer isDirectCast = purchaseRequestVO.getIsDirectCast();
            boolean diret = null != isDirectCast && isDirectCast == 1;
            List<PurchaseRequestDetailVO> materialsList = purchaseRequestVO.getMaterialsList();
            if (diret && CollectionUtils.isNotEmpty(materialsList)) {
                String soldOrgId = purchaseRequestVO.getSoldOrgId();
                String supplierOrgId = purchaseRequestVO.getSupplierOrgId();
                if (soldOrgId.equals(supplierOrgId)) {
                    return;
                }
                for (PurchaseRequestDetailVO purchaseRequestDetailVO : materialsList) {
                    String materialsNo = purchaseRequestDetailVO.getMaterialsNo();
                    MaterialsSupplierDO materialsSupplierDO = materialsSupplierMapper.findBySupplierOrgIdAndSalesCode(soldOrgId, supplierOrgId, materialsNo, purchaseRequestVO.getSalesCode());
                    if (materialsSupplierDO == null) {
                        throw new CommonBusiExceptions("零件:" + materialsNo + "不是所选供应商下的零件");
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(materialsList)) {
                Boolean selfMaterialFlag = false;
                if (null != isDirectCast && Integer.valueOf(0).equals(isDirectCast)) {
                    DataDictionaryVO dictVO = dataDictionaryService.itemByCode(SELF_MATERIAL_FILTER, orgId);
                    if (dictVO != null) {
                        selfMaterialFlag = true;
                    }
                }

                String supplier = purchaseRequestVO.getSupplierOrgId();
                String supplierOrgId = purchaseRequestVO.getSupplierOrgId();
                if (null != isDirectCast && Integer.valueOf(0).equals(isDirectCast) && selfMaterialFlag) {
                    supplier = orgId;
                } else {
                    if (companyInfoService.info(supplier) == null) {
                        return;
                    }
                }
                //是自制件基础机：0-否，1-是自制件 2基础机
                int selfmade = purchaseRequestVO.getSelfMade();
                for (PurchaseRequestDetailVO purchaseRequestDetailVO : materialsList) {
                    String materialsNo = purchaseRequestDetailVO.getMaterialsNo();
                    PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, supplier);
                    boolean isMDirect = (null != priMaterialsDO.getIsDirectCast() && 1 == priMaterialsDO.getIsDirectCast()) || (null != priMaterialsDO.getIsDirectCastHF() && 1 == priMaterialsDO.getIsDirectCastHF());
                    int count = priMaterialsMapper.getOemMaterialsCount(materialsNo, orgId, purchaseRequestVO.getCreateOrgId());
                    if (priMaterialsDO == null && count == 0) {
                        throw new CommonBusiExceptions("零件:" + materialsNo + "不是所选接收单位下的零件且也不是相应主机厂零件");
                    }

                    if (1 == selfmade && (null == priMaterialsDO.getSelfMade() || 0 == priMaterialsDO.getSelfMade())) {
                        throw new CommonBusiExceptions("零件:" + materialsNo + "不是自制零件");
                    } else if (0 == selfmade && (null != priMaterialsDO.getSelfMade() && 1 == priMaterialsDO.getSelfMade())) {
                        throw new CommonBusiExceptions("零件:" + materialsNo + "是自制零件");
                    }

                    if (baseMach && (null == priMaterialsDO.getBasicMachine() || 1 != priMaterialsDO.getBasicMachine())) {
                        throw new CommonBusiExceptions("零件:" + materialsNo + "不是基础机零件");
                    }
                    if ((salfMade || baseMach) && StringUtils.isNotBlank(sendCompanyCode)) {
                        if (StringUtils.isBlank(priMaterialsDO.getSelfMadeCompanyCode()) || !sendCompanyCode.equals(priMaterialsDO.getSelfMadeCompanyCode())) {
                            throw new CommonBusiExceptions("零件:" + materialsNo + "不是" + purchaseRequestVO.getSendCompanyName() + "(" + purchaseRequestVO.getSendCompanyCode() + ")的零件");
                        }
                    }
                    if (diret) {
                        if (null == priMaterialsDO.getIsDirectCastHF() || 1 != priMaterialsDO.getIsDirectCastHF()) {
                            throw new CommonBusiExceptions("零件:" + materialsNo + "非直投（合肥）");
                        }
                    } else {
                        if (isMDirect) {
                            throw new CommonBusiExceptions("零件:" + materialsNo + "为直投零件");
                        }
                    }
                    //扩充零件
                    if (null != isDirectCast && Integer.valueOf(0).equals(isDirectCast) && selfMaterialFlag && operate != null && "submit".equals(operate)) {
                        enExtendMaterials(priMaterialsDO, supplierOrgId);
                    }
                }
            }
        }
    }

    //扩充零件
    private void enExtendMaterials(PriMaterialsDO fromPriMaterialsDO, String toOrgId) {
        PriMaterialsDO priMaterialsDO = new PriMaterialsDO();
        BeanUtils.copyProperties(fromPriMaterialsDO, priMaterialsDO);
        priMaterialsDO.setStockLocation(null);
        priMaterialsDO.setOrgId(toOrgId);
        priMaterialsDO.setStandardPrice(new BigDecimal("0"));
        priMaterialsDO.setPrice(new BigDecimal("0"));

        int count = priMaterialsMapper.count(fromPriMaterialsDO.getMaterialsNo(), toOrgId);
        if (count == 0) {
            priMaterialsMapper.insert(priMaterialsDO);
        }
    }

    /**
     * 外部接口调用添加采购订单
     *
     * @param model
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public String insert4External(PurchaseRequestExternalVO model) throws Exception {
        String checkResult = checkRequestExternalParam(model);
        if (StringUtils.isNotBlank(checkResult)) {
            throw new Exception(checkResult);
        }
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            throw new Exception("获取主键失败");
        }
        String billId = textResult.getValue();
        String billNo = genDocumentService.getDocumentNo(BillDesc.PurchaseNo);

        if (SOURCE_E_COMMERCE.equals(model.getSource())) {
            saveFromEStore(model, billId, billNo);
        } else if (SOURCE_CRM.equals(model.getSource())) {
            saveFromCRM(model, billId, billNo);
        } else if (SOURCE_JCK.equals(model.getSource())) {
            saveFromJCK(model, billId, billNo);
        } else if (SOURCE_GSS.equals(model.getSource())) {
            saveFromGSS(model, billId, billNo);
            // GGS调用，返回订单ID+订单no（2020-02-28调整）
            billNo = billId + "-" + billNo;
        } else {
            //若有待续
            throw new Exception("source错误");
        }
        return billNo;
    }

    /**
     * 挖机CRM数据
     *
     * @param model
     * @param billId
     * @param billNo
     */
    private void saveFromGSS(PurchaseRequestExternalVO model, String billId, String billNo)
            throws Exception {
        PurchaseRequestDO purchaseRequestDO = new PurchaseRequestDO();

        CompanyInfoDO company = companyInfoMapper.itemBySap(model.getSapCode());
        if (null == company) {
            throw new Exception("未查询到主机厂信息, sapCode为：" + model.getSapCode());
        }
        purchaseRequestDO.setCreateOrgId(company.getOrgId());
        purchaseRequestDO = fillPurchaseInfo(purchaseRequestDO, model, company.getOrgId());
        purchaseRequestDO.setSupplierOrgId(company.getOrgId());
        purchaseRequestDO.setSupplierOrgName(company.getCompanyName());
//        purchaseRequestDO.setPurchaseType(String.valueOf(PurchaseType.replenish.getCode()));//补库
        // 系统生成
        purchaseRequestDO.setCreateId(GSS_USER_ID);
        purchaseRequestDO.setCreateName("gss接口");
        purchaseRequestDO.setBillId(billId);
        purchaseRequestDO.setBillStatus(PurchaseRequestBillStatusEnum.DRAFT.getStatus());
        purchaseRequestDO.setStatusDesc(PurchaseRequestBillStatusEnum.DRAFT.getStatusDesc());
        purchaseRequestDO.setDel(false);
        purchaseRequestDO.setRemark(model.getRemark());
        purchaseRequestDO.setCreateDate(new Date());
        BigDecimal totalValue = saveDetailDO(model.getMaterials(), company.getOrgId(), billId);
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setSettlementValue(totalValue);
        purchaseRequestDO.setBillNo(billNo);
        purchaseRequestDO.setReceiverAddress(model.getReceiverAddress());
        purchaseRequestDO.setReceiverTel(model.getReceiverTel());
        purchaseRequestDO.setReceiverName(model.getReceiverName());

        String appTimeStr = model.getApplicationTime();
        if (StringUtils.isNotBlank(appTimeStr)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            purchaseRequestDO.setApplicationTime(sdf.parse(appTimeStr));
        }
        purchaseRequestMapper.insert(purchaseRequestDO);
    }

    /**
     * GSS代理商端
     *
     * @param model
     */
    public String saveFromGSSAgent(PurchaseRequestExternalVO model)
            throws Exception {
        PurchaseRequestDO purchaseRequestDO = new PurchaseRequestDO();
        CompanyInfoDO company = companyInfoMapper.itemBySap(model.getSapCode());
        if (null == company) {
            throw new Exception("未查询到主机厂信息, sapCode为：" + model.getSapCode());
        }
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            throw new Exception("获取主键失败");
        }
        String billId = textResult.getValue();
        String billNo = genDocumentService.getDocumentNo(BillDesc.PurchaseNo);
        CompanyInfoDO purchaseCom = companyInfoMapper.itemBySap(model.getAgentSapCode());
        if (null != purchaseCom) {
            purchaseRequestDO.setPurchaseOrgId(purchaseCom.getOrgId());
            purchaseRequestDO.setPurchaseOrgName(purchaseCom.getCompanyName());
            purchaseRequestDO.setCreateOrgId(purchaseCom.getOrgId());
        } else {
            CompanyDealerDO dealerDO = getDealerCompany(company.getOrgId(), model.getAgentSapCode(), model.getAgentName());
            if (null != dealerDO) {
                purchaseRequestDO.setPurchaseOrgId(dealerDO.getPlatOrgId());
                purchaseRequestDO.setPurchaseOrgName(dealerDO.getCompanyName());
                purchaseRequestDO.setCreateOrgId(dealerDO.getOrgId());
            } else {
                purchaseRequestDO.setPurchaseOrgName(model.getAgentName());
            }
        }

        purchaseRequestDO.setSupplierOrgId(company.getOrgId());
        purchaseRequestDO.setSupplierOrgName(company.getCompanyName());
//        purchaseRequestDO.setPurchaseType(String.valueOf(PurchaseType.replenish.getCode()));//补库
        // 系统生成
        purchaseRequestDO.setCreateId(GSS_AGENT_ID);
        purchaseRequestDO.setCreateName("gss代理商");
        purchaseRequestDO.setBillId(billId);
        purchaseRequestDO.setBillStatus(PurchaseRequestBillStatusEnum.DRAFT.getStatus());
        purchaseRequestDO.setStatusDesc(PurchaseRequestBillStatusEnum.DRAFT.getStatusDesc());
        purchaseRequestDO.setDel(false);
        purchaseRequestDO.setRemark(model.getRemark());
        purchaseRequestDO.setCreateDate(new Date());
        BigDecimal totalValue = saveDetailDO(model.getMaterials(), company.getOrgId(), billId);
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setSettlementValue(totalValue);
        purchaseRequestDO.setBillNo(billNo);
        purchaseRequestDO.setReceiverAddress(model.getReceiverAddress());
        purchaseRequestDO.setReceiverTel(model.getReceiverTel());
        purchaseRequestDO.setReceiverName(model.getReceiverName());

        String appTimeStr = model.getApplicationTime();
        if (StringUtils.isNotBlank(appTimeStr)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            purchaseRequestDO.setApplicationTime(sdf.parse(appTimeStr));
        }
        purchaseRequestMapper.insert(purchaseRequestDO);
        return billId + "-" + billNo;
    }

    private PurchaseRequestDO fillPurchaseInfo(PurchaseRequestDO purchaseRequestDO, PurchaseRequestExternalVO model, String orgId) {
        CompanyInfoDO purchaseCom = companyInfoMapper.itemBySap(model.getAgentSapCode());
        if (null != purchaseCom) {
            purchaseRequestDO.setPurchaseOrgId(purchaseCom.getOrgId());
            purchaseRequestDO.setPurchaseOrgName(purchaseCom.getCompanyName());
            purchaseRequestDO.setCreateOrgId(purchaseCom.getOrgId());
        } else {
            CompanyDealerDO dealerDO = getDealerCompany(orgId, model.getAgentSapCode(), model.getAgentName());
            if (null != dealerDO) {
                purchaseRequestDO.setPurchaseOrgId(dealerDO.getDealerOrgId());
                purchaseRequestDO.setPurchaseOrgName(dealerDO.getCompanyName());
            } else {
                purchaseRequestDO.setPurchaseOrgName(model.getAgentName());
            }
        }
        return purchaseRequestDO;
    }

    private CompanyDealerDO getDealerCompany(String orgId, String dealerCode, String dealerName) {
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByDealerCode(orgId, dealerCode);
        if (null == companyDealerDO) {
            companyDealerDO = companyDealerMapper.getDealerByOrgIdCompanyName(orgId, dealerName);
        }
        return companyDealerDO;
    }

    /**
     * 徐工电商数据
     *
     * @param model
     * @param billId
     * @param billNo
     */
    private void saveFromEStore(PurchaseRequestExternalVO model, String billId, String billNo)
            throws Exception {
        PurchaseRequestDO purchaseRequestDO = new PurchaseRequestDO();
        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(model.getStoreSapCode());
        if (null == companyInfoDO) {
            throw new Exception("未查询到此代理商信息，sapCode为：" + model.getStoreSapCode());
        }
        //汉旗
        purchaseRequestDO.setSupplierOrgId(companyInfoDO.getOrgId());
        purchaseRequestDO.setSupplierOrgName(companyInfoDO.getCompanyName());
        purchaseRequestDO.setPurchaseOrgName(model.getUserName());
        //紧急
        purchaseRequestDO.setPurchaseType(String.valueOf(PurchaseType.exigency.getCode()));
        purchaseRequestDO.setReceiverName(model.getUserName());
        purchaseRequestDO.setReceiverTel(model.getPhone());
        purchaseRequestDO.setReceiverAddress(model.getAddress());
        // 系统生成
        purchaseRequestDO.setCreateId("000001");
        purchaseRequestDO.setCreateName("xcmg-E-store");
        BigDecimal totalValue = saveDetailDO(model.getMaterials(), companyInfoDO.getOrgId(), billId);
        purchaseRequestDO.setBillId(billId);
        purchaseRequestDO.setBillStatus(PurchaseRequestBillStatusEnum.SUBMITED.getStatus());
        purchaseRequestDO.setStatusDesc(PurchaseRequestBillStatusEnum.SUBMITED.getStatusDesc());
        purchaseRequestDO.setDel(false);
        purchaseRequestDO.setRemark(model.getRemark());
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setSettlementValue(totalValue);
        purchaseRequestDO.setCreateDate(new Date());
        purchaseRequestDO.setBillNo(billNo);
        purchaseRequestMapper.insert(purchaseRequestDO);
    }

    /**
     * 挖机CRM数据
     *
     * @param model
     * @param billId
     * @param billNo
     */
    private void saveFromCRM(PurchaseRequestExternalVO model, String billId, String billNo)
            throws Exception {
        PurchaseRequestDO purchaseRequestDO = new PurchaseRequestDO();
        CompanyInfoDO crmCompany = companyInfoMapper.itemBySap(model.getAgentSapCode());
        if (null == crmCompany) {
            throw new Exception("未查询到此代理商信息，sapCode为：" + model.getAgentSapCode());
        }
        CompanyInfoDO company = companyInfoMapper.itemBySap(model.getSapCode());
        if (null == company) {
            throw new Exception("未查询到主机厂信息, sapCode为：" + model.getSapCode());
        }
        purchaseRequestDO.setPurchaseOrgId(crmCompany.getOrgId());
        purchaseRequestDO.setPurchaseOrgName(crmCompany.getCompanyName());
        purchaseRequestDO.setSupplierOrgId(company.getOrgId());//挖机
        purchaseRequestDO.setSupplierOrgName(company.getCompanyName());
        purchaseRequestDO.setPurchaseType(String.valueOf(PurchaseType.replenish.getCode()));//补库

        // 系统生成
        purchaseRequestDO.setCreateId("000001");
        purchaseRequestDO.setCreateName("xgwj-crm");
        purchaseRequestDO.setBillId(billId);
        purchaseRequestDO.setBillStatus(PurchaseRequestBillStatusEnum.DRAFT.getStatus());
        purchaseRequestDO.setStatusDesc(PurchaseRequestBillStatusEnum.DRAFT.getStatusDesc());
        purchaseRequestDO.setDel(false);
        purchaseRequestDO.setRemark(model.getRemark());
        purchaseRequestDO.setCreateDate(new Date());
        BigDecimal totalValue = saveDetailDO(model.getMaterials(), company.getOrgId(), billId);
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setSettlementValue(totalValue);
        purchaseRequestDO.setBillNo(billNo);
        purchaseRequestDO.setReceiverAddress(model.getReceiverAddress());
        purchaseRequestDO.setReceiverTel(model.getReceiverTel());
        purchaseRequestDO.setReceiverName(model.getReceiverName());
        purchaseRequestDO.setApplicationNo(model.getApplicationNo());
        purchaseRequestDO.setServiceNo(model.getServiceNo());
        purchaseRequestDO.setNotificationNo(model.getNotificationNo());
        purchaseRequestDO.setDispatcherName(model.getDispatcherName());
        purchaseRequestDO.setShippingMethod(model.getShippingMethod());
        purchaseRequestDO.setCreateOrgId(crmCompany.getOrgId());

        String appTimeStr = model.getApplicationTime();
        if (StringUtils.isNotBlank(appTimeStr)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            purchaseRequestDO.setApplicationTime(sdf.parse(appTimeStr));
        }
        purchaseRequestDO.setDeviceNo(model.getDeviceNo());
        purchaseRequestDO.setApplicationQty(model.getApplicationQty());
        purchaseRequestMapper.insert(purchaseRequestDO);
    }

    /**
     * 进出口调用
     *
     * @param model
     * @param billId
     * @param billNo
     */
    private void saveFromJCK(PurchaseRequestExternalVO model, String billId, String billNo)
            throws Exception {
        PurchaseRequestDO purchaseRequestDO = new PurchaseRequestDO();
        CompanyInfoDO jckCompany = companyInfoMapper.itemBySap(model.getAgentSapCode());
        if (null == jckCompany) {
            throw new Exception("未查询到公司信息，sapCode为：" + model.getAgentSapCode());
        }
        CompanyInfoDO company = companyInfoMapper.itemBySap(model.getSapCode());
        if (null == company) {
            throw new Exception("未查询到主机厂信息, sapCode为：" + model.getSapCode());
        }
        purchaseRequestDO.setPurchaseOrgId(jckCompany.getOrgId());
        purchaseRequestDO.setPurchaseOrgName(jckCompany.getCompanyName());
        purchaseRequestDO.setSupplierOrgId(company.getOrgId());//挖机
        purchaseRequestDO.setSupplierOrgName(company.getCompanyName());
        //进出口默认为紧急
        purchaseRequestDO.setPurchaseType(String.valueOf(PurchaseType.exigency.getCode()));


        purchaseRequestDO.setReceiverName(model.getReceiverName());
        purchaseRequestDO.setReceiverTel(model.getReceiverTel());
        purchaseRequestDO.setReceiverFax(model.getReceiverFax());
        purchaseRequestDO.setReceiverAddress(model.getReceiverAddress());
        purchaseRequestDO.setApplicationName(model.getApplicationName());
        // 系统生成
        purchaseRequestDO.setCreateId("000001");
        purchaseRequestDO.setCreateName("进出口");
        purchaseRequestDO.setBillId(billId);
        purchaseRequestDO.setBillStatus(PurchaseRequestBillStatusEnum.SUBMITED.getStatus());
        purchaseRequestDO.setStatusDesc(PurchaseRequestBillStatusEnum.SUBMITED.getStatusDesc());
        purchaseRequestDO.setDel(false);
        purchaseRequestDO.setRemark(model.getRemark());
        purchaseRequestDO.setCreateDate(new Date());
        BigDecimal totalValue = saveDetailDO(model.getMaterials(), company.getOrgId(), billId);
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setSettlementValue(totalValue);
        purchaseRequestDO.setBillNo(billNo);

        purchaseRequestDO.setApplicationNo(model.getApplicationNo());

        String appTimeStr = model.getApplicationTime();
        if (StringUtils.isNotBlank(appTimeStr)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            purchaseRequestDO.setApplicationTime(sdf.parse(appTimeStr));
        }
        purchaseRequestDO.setDeviceNo(model.getDeviceNo());
        purchaseRequestDO.setApplicationQty(model.getApplicationQty());

        purchaseRequestDO.setDispatcherName(model.getDispatcherName());

        purchaseRequestMapper.insert(purchaseRequestDO);
    }

    private BigDecimal saveDetailDO(List<PurchaseRequestDetailVO> materialsVOS, String orgId, String billId)
            throws Exception {
        PurchaseRequestDetailDO detailDO = new PurchaseRequestDetailDO();
        BigDecimal totalValue = BigDecimal.ZERO;
        for (PurchaseRequestDetailVO detailVO : materialsVOS) {
            PriMaterialsDO materialsDO = priMaterialsMapper.itemByNo(detailVO.getMaterialsNo(), orgId);
            if (null == materialsDO) {
                throw new Exception("未查询到零件：" + detailVO.getMaterialsNo() + ",comId:" + orgId);
            }
            detailDO.setBillId(billId);
            detailDO.setMaterialsNo(detailVO.getMaterialsNo());
            detailDO.setQty(detailVO.getQty());
            detailDO.setStatus(INBOUND_STATUS_NO);
            detailDO.setMaterialsDes(materialsDO.getMaterialsDes());
            detailDO.setUnit(materialsDO.getUnit());
            detailDO.setPrice(materialsDO.getPrice());
            BigDecimal settlePrice = null;
            if (null == detailVO.getSettlementPrice()) {
                settlePrice = materialsDO.getPrice();
            } else {
                settlePrice = DecimalUtil.roundDecimal4Enter(detailVO.getSettlementPrice());
            }
            detailDO.setSettlementPrice(settlePrice);
            BigDecimal amount = detailVO.getQty().multiply(settlePrice);
            detailDO.setApplyTotalPrice(amount);
            totalValue = totalValue.add(amount);
            purchaseRequestDetailMapper.insert(detailDO);
        }
        return totalValue;
    }

    /**
     * 接口数据校验
     *
     * @param model
     * @return
     */
    private String checkRequestExternalParam(PurchaseRequestExternalVO model) {
        if (CollectionUtils.isEmpty(model.getMaterials())) {
            return "零件不能为空";
        }

        if (null == model.getSource()) {
            return "source不能为空";
        }

        if (model.isFromECommerce()) {

            if (null == model.getStoreSapCode()) {
                return "代理商sapCode不能为空";
            }

            if (null == model.getPhone()) {
                return "电话不能为空";
            }
            if (null == model.getAddress()) {
                return "地址不能为空";
            }

        } else {
            if (null == model.getAgentSapCode()) {
                return "代理商sapCode不能为空";
            }
        }
        return StringUtils.EMPTY;
    }

    private void insetLog(String userName, String usertId, String message, PurchaseRequestDO purchaseRequestDO) throws Exception {
        PurchaseRequestLogDO purchaseRequestLogDO = new PurchaseRequestLogDO();
        if (StringUtil.isNullOrEmpty(userName)) {
            purchaseRequestLogDO.setOperationName(userName);
        } else {
            ActionResult userAuth = authClient.getUserDetail(usertId);
            UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
            if (userInfo != null) {
                purchaseRequestLogDO.setOperationName(userInfo.getName());
            }
        }
        ActionResult<String> logResult = fastGenClient.textGuid();
        if (logResult.getCode() != ErrorCode.Success.getCode()) {
            return;
        }
        purchaseRequestLogDO.setId(logResult.getValue());
        purchaseRequestLogDO.setOperationTime(new Date());
        purchaseRequestLogDO.setBillId(purchaseRequestDO.getBillId());
        purchaseRequestLogDO.setBillNo(purchaseRequestDO.getBillNo());
        purchaseRequestLogDO.setMessage(message);
        purchaseRequestLogMapper.insert(purchaseRequestLogDO);
    }


    /**
     * 更新采购订单价格
     *
     * @param purchaseRequestVO
     * @param orgId
     * @param type              来源：0进出口采购订单零件替换   1主机厂销售订单零件替换
     * @return
     * @throws Exception
     */
    public ErrorCode updateTotalValue(PurchaseRequestVO purchaseRequestVO, String orgId, Integer type) throws Exception {
        //直投校验零件是否存在
        checkMaterialExist(purchaseRequestVO, orgId, null);

        if (purchaseRequestVO.getBillId() == null || purchaseRequestVO.getBillId() == "") {
            return ErrorCode.PurchaseBillIdNotExists;
        }
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(purchaseRequestVO.getBillId());
        if (purchaseRequestDO == null) {
            return ErrorCode.PurchaseInfoNotExists;
        }
        if (type == 0) {
            SaleIntentionDO saleIntentionDO = saleIntentionMapper.itemByPurchaseNo(purchaseRequestDO.getBillNo(), purchaseRequestDO.getSupplierOrgId());
            if (saleIntentionDO != null) {
                throw new Exception("该采购单已创建销售订单，不能编辑");
            }
        }

        PurchaseRequestVO record = new PurchaseRequestVO();
        record.setDirectSourceOrder(purchaseRequestDO.getBillNo());
        record.setPurchaseOrgId(purchaseRequestDO.getSupplierOrgId());
        if (!ListUtil.isNullOrEmpty(purchaseRequestMapper.list(record))) {
            throw new Exception("该采购单已创建直投单，不能编辑");
        }
        purchaseRequestDO.setTotalValue(purchaseRequestVO.getTotalValue());
        purchaseRequestDO.setSettlementValue(purchaseRequestVO.getSettlementValue());
        purchaseRequestDO.setUpdateDate(purchaseRequestVO.getUpdateDate());
        purchaseRequestDO.setUpdateId(purchaseRequestVO.getUpdateId());
        return purchaseRequestMapper.update(purchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    @Transactional
    public ErrorCode update(PurchaseRequestVO purchaseRequestVO, String orgId, String operate) throws Exception {
        //直投校验零件是否存在
        checkMaterialExist(purchaseRequestVO, orgId, operate);

        if (purchaseRequestVO.getBillId() == null || purchaseRequestVO.getBillId() == "") {
            return ErrorCode.PurchaseBillIdNotExists;
        }
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(purchaseRequestVO.getBillId());
        if (purchaseRequestDO == null) {
            return ErrorCode.PurchaseInfoNotExists;
        }
        SaleIntentionDO saleIntentionDO = saleIntentionMapper.itemByPurchaseNo(purchaseRequestDO.getBillNo(), purchaseRequestDO.getSupplierOrgId());
        if (saleIntentionDO != null) {
            throw new Exception("该采购单已创建销售订单，不能编辑");
        }
        PurchaseRequestVO record = new PurchaseRequestVO();
        record.setDirectSourceOrder(purchaseRequestDO.getBillNo());
        record.setPurchaseOrgId(purchaseRequestDO.getSupplierOrgId());
        if (!ListUtil.isNullOrEmpty(purchaseRequestMapper.list(record))) {
            throw new Exception("该采购单已创建直投单，不能编辑");
        }
        if (purchaseRequestDO.getBillStatus().equals(PurchaseStatus.AuditPass.toString())) {
            purchaseRequestVO.setBillStatus(purchaseRequestDO.getBillStatus());
        }
        if ((purchaseRequestDO.getBillStatus().equals(PurchaseStatus.AuditRefused.toString()) || purchaseRequestDO.getBillStatus().equals(PurchaseStatus.RefusedSumbit.toString())) && purchaseRequestVO.getBillStatus().equals(PurchaseStatus.WaitAudit.toString())) {
            purchaseRequestVO.setBillStatus(PurchaseStatus.RefusedSumbit.toString());
        }
        if (purchaseRequestVO.getSeller() != null && !purchaseRequestVO.getSeller() && PurchaseStatus.WaitAudit.toString().equals(purchaseRequestVO.getBillStatus()) && !GSS_USER_ID.equals(purchaseRequestDO.getCreateId())) {
            CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(purchaseRequestVO.getPurchaseOrgId(), purchaseRequestVO.getSupplierOrgId());
            if (supplierDO == null) {
                return ErrorCode.IllegalArument;
            }
            //如果供应商不是平台企业直接置为审核通过
            if (!supplierDO.getIsPlatCompany()) {
                purchaseRequestVO.setBillStatus(PurchaseStatus.AuditPass.toString());
            }
        }
        ErrorCode code = ErrorCode.Success;
        purchaseRequestDetailMapper.deleteByBillId(purchaseRequestVO.getBillId());
        DataDictionaryDO auditDataDictionaryDO = dataDictionaryMapper.itemByCode(PurchaseStatus.Name.toString(), purchaseRequestVO.getBillStatus());
        if (auditDataDictionaryDO != null) {
            purchaseRequestVO.setStatusDesc(auditDataDictionaryDO.getName());
        }
//        DataDictionaryDO typeDataDictionaryDO = dataDictionaryMapper.itemByCode("CGJB", purchaseRequestVO.getPurchaseType());
//        if (typeDataDictionaryDO != null) {
//            purchaseRequestVO.setTypeDesc(typeDataDictionaryDO.getName());
//        }
        List<PurchaseRequestDetailVO> detailList = purchaseRequestVO.getMaterialsList();
        BigDecimal totalValue = new BigDecimal("0");

        List<PurchaseRequestDetailDO> purchaseRequestDetailDOS = new ArrayList<>();

        if (detailList != null && detailList.size() > 0) {
            for (PurchaseRequestDetailVO detail : detailList) {
                String isReplaceMaterial = detail.getIsReplaceMaterial();
                detail.setSettlementPrice(detail.getSettlementPrice().multiply(new BigDecimal("100")));
                detail.setPrice(detail.getPrice().multiply(new BigDecimal("100")));
                BigDecimal qty = new BigDecimal(detail.getQty().toString());
                BigDecimal amont = BigDecimal.valueOf(detail.getSettlementPrice().multiply(qty).doubleValue());
                totalValue = totalValue.add(amont);
                detail.setApplyTotalPrice(amont);
                detail.setBillId(purchaseRequestVO.getBillId());
                PurchaseRequestDetailDO purchaseRequestDetailDO = getDetailDO(detail);
                code = purchaseRequestDetailMapper.insert(purchaseRequestDetailDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
                if (code != ErrorCode.Success) {
                    return code;
                }
                if (StringUtils.equals("1", isReplaceMaterial)) {
                    //更新上游的销售订单
                    //根据采购订单查找销售订单
                    String purchaseContractNo = purchaseRequestVO.getPurchaseContractNo();
                    if (StringUtils.isNotBlank(purchaseContractNo)) {
                        SaleIntentionDO intentionDO = saleIntentionMapper.itemBySaleNo(purchaseContractNo);
                        if (intentionDO != null) {
                            //获取销售订单明细
                            List<SaleIntentionDetailDO> saleIntentionDetailDOS = saleIntentionDetailMapper.list(intentionDO.getId());
                            BigDecimal detailPrice = detail.getPrice();
                            if (detailPrice == null) {
                                detailPrice = BigDecimal.ZERO;
                            }
                            for (SaleIntentionDetailDO saleIntentionDetailDO : saleIntentionDetailDOS) {
                                if (StringUtils.equals(saleIntentionDetailDO.getMaterialsNo(), detail.getOriginalMaterialsNo())) {
                                    saleIntentionDetailDO.setOriginalMaterialsNo(detail.getOriginalMaterialsNo());
                                    saleIntentionDetailDO.setMaterialsNo(detail.getMaterialsNo());
                                    saleIntentionDetailDO.setMaterialsDes(detail.getMaterialsDes());
                                    saleIntentionDetailDO.setPrice(detailPrice);
                                    saleIntentionDetailDO.setUnit(detail.getUnit());
                                    saleIntentionDetailDO.setApplyTotalPrice(detailPrice.multiply(saleIntentionDetailDO.getQty()));
                                    saleIntentionDetailDO.setUnitPriceAfterAdjust(detail.getSettlementPrice());
                                    saleIntentionDetailDO.setTotalPriceAfterAdjust(saleIntentionDetailDO.getUnitPriceAfterAdjust().multiply(saleIntentionDetailDO.getQty()));
                                    saleIntentionDetailMapper.update(saleIntentionDetailDO);
                                }
                            }

                            //计算销售订单总金额
                            BigDecimal totalPrice = BigDecimal.ZERO;
                            BigDecimal discountPrice = BigDecimal.ZERO;
                            for (SaleIntentionDetailDO saleIntentionDetailDO : saleIntentionDetailDOS) {
                                totalPrice = totalPrice.add(saleIntentionDetailDO.getPrice().multiply(saleIntentionDetailDO.getQty()));
                                discountPrice = discountPrice.add(saleIntentionDetailDO.getUnitPriceAfterAdjust().multiply(saleIntentionDetailDO.getQty()));
                            }
                            intentionDO.setTotalSettlementPrice(totalPrice);
                            intentionDO.setTotalDiscountPrice(discountPrice);

                            saleIntentionMapper.update(intentionDO);
                        }
                    }
                }

                purchaseRequestDetailDOS.add(purchaseRequestDetailDO);
            }
        }
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setSettlementValue(totalValue);
        purchaseRequestDO.setDispatcherId(purchaseRequestVO.getDispatcherId());
        purchaseRequestDO.setDispatcherName(purchaseRequestVO.getDispatcherName());
        purchaseRequestDO.setPurchaseType(purchaseRequestVO.getPurchaseType());
        purchaseRequestDO.setShippingMethod(purchaseRequestVO.getShippingMethod());
        purchaseRequestDO.setShippingMethodId(purchaseRequestVO.getShippingMethodId());
        purchaseRequestDO.setReceiverName(purchaseRequestVO.getReceiverName());
        purchaseRequestDO.setReceiverAddress(purchaseRequestVO.getReceiverAddress());
        purchaseRequestDO.setReceiverFax(purchaseRequestVO.getReceiverFax());
        purchaseRequestDO.setReceiverTel(purchaseRequestVO.getReceiverTel());
        purchaseRequestDO.setSelfMade(purchaseRequestVO.getSelfMade());
        String addressCode = purchaseRequestVO.getAddressCode();
        if (!StringUtils.isEmpty(addressCode)) {
            purchaseRequestDO.setAddressCode(addressCode);
        }
        purchaseRequestDO.setRemark(purchaseRequestVO.getRemark());
        purchaseRequestDO.setBillStatus(purchaseRequestVO.getBillStatus());
        purchaseRequestDO.setUpdateId(purchaseRequestVO.getUpdateId());
        purchaseRequestDO.setStatusDesc(purchaseRequestVO.getStatusDesc());
        purchaseRequestDO.setTypeDesc(purchaseRequestVO.getTypeDesc());
        purchaseRequestDO.setPurchaseGroup(purchaseRequestVO.getPurchaseGroup());
        purchaseRequestDO.setUpdateDate(new Date());
        purchaseRequestDO.setSubmitDate(purchaseRequestVO.getSubmitDate());
        purchaseRequestDO.setCountry(purchaseRequestVO.getCountry());
        purchaseRequestDO.setModel(purchaseRequestVO.getModel());
        purchaseRequestDO.setIsImprove(purchaseRequestVO.getIsImprove());
        purchaseRequestDO.setPurchaseTypeChildId(purchaseRequestVO.getPurchaseTypeChildId());
        purchaseRequestDO.setPurchaseTypeChildName(purchaseRequestVO.getPurchaseTypeChildName());
        purchaseRequestDO.setSendTypeChildId(purchaseRequestVO.getSendTypeChildId());
        purchaseRequestDO.setSendTypeChildName(purchaseRequestVO.getSendTypeChildName());
        purchaseRequestDO.setSapInArea(purchaseRequestVO.getSapInArea());
        purchaseRequestDO.setDeliveryDate(purchaseRequestVO.getDeliveryDate());
        purchaseRequestDO.setPurchaseContractNo(purchaseRequestVO.getPurchaseContractNo());
        purchaseRequestDO.setSendCompanyCode(purchaseRequestVO.getSendCompanyCode());
        purchaseRequestDO.setSendCompanyName(purchaseRequestVO.getSendCompanyName());
        purchaseRequestDO.setCompanyType(purchaseRequestVO.getCompanyType());
        purchaseRequestDO.setTotalQuantity(purchaseRequestVO.getTotalQuantity());
        purchaseRequestDO.setDeptCode(purchaseRequestVO.getDeptCode());
        purchaseRequestDO.setDeptName(purchaseRequestVO.getDeptName());
        purchaseRequestDO.setPurchaseCode(purchaseRequestVO.getPurchaseCode());
        purchaseRequestDO.setPurchaseName(purchaseRequestVO.getPurchaseName());
        Integer forward = purchaseRequestVO.getForward();
        forward = forward == null ? 0 : forward;
        purchaseRequestDO.setForward(forward);

        if (StringUtil.isNullOrEmpty(purchaseRequestDO.getDirectSourceOrder()) && StringUtil.isNullOrEmpty(purchaseRequestDO.getDeliveryOrgId())) {
            purchaseRequestDO.setDeliveryOrgId(purchaseRequestDO.getPurchaseOrgId());
            purchaseRequestDO.setDeliveryOrgName(purchaseRequestDO.getPurchaseOrgName());
        }
        ActionResult userAuth = authClient.getUserDetail(purchaseRequestDO.getUpdateId());
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        if (userInfo != null) {
            purchaseRequestDO.setUpdateName(userInfo.getName());
        }
        code = purchaseRequestMapper.update(purchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
        if (!purchaseRequestDO.getBillStatus().equals(PurchaseStatus.Saved.toString())) {
            String message = "[提交订单]";
            if (purchaseRequestDO.getBillStatus().equals(PurchaseStatus.RefusedSumbit.toString())) {
                message = "[驳回再提交]";
            }
            String userName = "";
            if (userInfo != null) {
                userName = userInfo.getName();
            }
            insetLog(userName, purchaseRequestDO.getUpdateId(), message, purchaseRequestDO);

            // 生成壳牌订单，内部判断是否需要生成
//            genShellOrder(purchaseRequestDO, purchaseRequestDetailDOS);
        }
        return code;
    }

//    /**
//     * 生成壳牌订单
//     *
//     * @param requestDO
//     * @param detailDOS
//     * @throws Exception
//     */
//    private void genShellOrder(PurchaseRequestDO requestDO, List<PurchaseRequestDetailDO> detailDOS) throws Exception {
//        if (!needGenShellOrder(requestDO)) {
//            return;
//        }
//        PurOrderParams params = fillPurchaseOrder(requestDO, detailDOS);
//        LogHelper.monitor("PurchaseRequestService#genShellOrder:" + params.toString());
//        shellService.genShellOrder(params);
//        // 生成壳牌订单后，将订单状态改为已审核(2020-01-08朱经典要求，这样壳牌就不用操作我们系统来审核了)
//        requestDO.setBillStatus(PurchaseStatus.AuditPass.toString());
//        purchaseRequestMapper.update(requestDO);
//    }

    /**
     * 是否需要生成壳牌订单：采购方是挖机，并且供货方是壳牌
     *
     * @param requestDO
     * @return
     */
    private boolean needGenShellOrder(PurchaseRequestDO requestDO) {
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(requestDO.getPurchaseOrgId());
        if (null == companyInfoDO) {
            return false;
        }
        return CompanyUtil.isWJSapCode(companyInfoDO.getSapCode()) && CompanyUtil.isShell(requestDO.getSupplierOrgId());
    }

    private PurOrderParams fillPurchaseOrder(PurchaseRequestDO requestDO, List<PurchaseRequestDetailDO> detailDOS) {
        PurOrderParams params = new PurOrderParams();
        if (StringUtils.isEmpty(requestDO.getDirectSourceOrder())) {
            params.setPurchaseNo(requestDO.getBillNo());
        } else {
            params.setPurchaseNo(requestDO.getDirectSourceOrder());
        }
        params.setPurchaseName(formatStr(requestDO.getPurchaseOrgName()));
        params.setSupplierName(formatStr(requestDO.getSupplierOrgName()));
        params.setShippingMethod(formatStr(requestDO.getShippingMethod()));
        params.setShippingCode(requestDO.getAddressCode());
        params.setCreateDate(new Date());
        params.setRemark(formatStr(requestDO.getRemark()));

        List<MaterialsDetail> details = new ArrayList<>();
        MaterialsDetail detail;
        for (PurchaseRequestDetailDO detailDO : detailDOS) {
            detail = new MaterialsDetail();
            detail.setMaterialsNo(formatStr(detailDO.getMaterialsNo()));
            detail.setQty(formatStr(String.valueOf(detailDO.getQty())));
            detail.setMaterialsDes(formatStr(detailDO.getMaterialsDes()));
            // 单位固定为EA
            detail.setUnit("EA");
            detail.setPrice(String.valueOf(DecimalUtil.roundDecimal4Output(detailDO.getPrice())));
            details.add(detail);
        }
        params.setMaterialsDetails(details);
        return params;
    }

    private String formatStr(String val) {
        if (StringUtils.isBlank(val)) {
            return "-";
        }
        return val;
    }

    @Transactional
    public ErrorCode adjust(PurchaseRequestVO purchaseRequestVO, String orgId) throws Exception {
        //直投校验零件是否存在
        checkMaterialExist(purchaseRequestVO, orgId, null);

        if (StringUtils.isBlank(purchaseRequestVO.getBillId())) {
            return ErrorCode.PurchaseBillIdNotExists;
        }
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(purchaseRequestVO.getBillId());
        if (purchaseRequestDO == null) {
            return ErrorCode.PurchaseInfoNotExists;
        }
        String billStatus = purchaseRequestDO.getBillStatus();
        if (!"2".equals(billStatus)) {
            return ErrorCode.UnreviewedNotAllowingAdjust;
        }
        //校验该采购订单创建入库单的数量与调整后数量大小
        List<PurchaseRequestDetailVO> materialsList = purchaseRequestVO.getMaterialsList();
        for (PurchaseRequestDetailVO purchaseRequestDetailVO : materialsList) {
            BigDecimal amount = purchaseRequestDetailVO.getQty();
            BigDecimal deliveryQty = purchaseRequestDetailVO.getSendQty();
            if (null == deliveryQty || deliveryQty.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            if (amount.compareTo(deliveryQty) < 0) {
                return ErrorCode.AdjustQtyNotInError;
            }
        }

        List<PurchaseRequestDetailDO> detailDOS = purchaseRequestDetailMapper.list(purchaseRequestVO.getBillId());
        List<PurchaseRequestDetailVO> detailList = purchaseRequestVO.getMaterialsList();
        BigDecimal totalValue = BigDecimal.ZERO;
        ErrorCode code;
        for (PurchaseRequestDetailVO detail : detailList
        ) {
            String isReplaceMaterial = detail.getIsReplaceMaterial();
            detail.setSettlementPrice(detail.getSettlementPrice().multiply(new BigDecimal("100")));
            detail.setPrice(detail.getPrice().multiply(new BigDecimal("100")));
            BigDecimal qty = new BigDecimal(detail.getQty().toString());
            BigDecimal amont = BigDecimal.valueOf(detail.getSettlementPrice().multiply(qty).doubleValue());
            totalValue = totalValue.add(amont);
            detail.setApplyTotalPrice(amont);
            detail.setBillId(purchaseRequestVO.getBillId());
            PurchaseRequestDetailDO detailDO = getDetailDO(detail);
            String materialsNo;

            if (StringUtils.equals("1", isReplaceMaterial)) {
                detailDOS.removeIf(s -> StringUtils.isNotBlank(detailDO.getBillId())
                        && s.getBillId().equals(detailDO.getBillId()) &&
                        s.getMaterialsNo().equals(detailDO.getOriginalMaterialsNo()));
                materialsNo = detailDO.getOriginalMaterialsNo();
            } else {
                detailDOS.removeIf(s -> StringUtils.isNotBlank(detailDO.getBillId())
                        && s.getBillId().equals(detailDO.getBillId()) &&
                        s.getMaterialsNo().equals(detailDO.getMaterialsNo()));
                materialsNo = detailDO.getMaterialsNo();
            }

            String billId = detailDO.getBillId();
            PurchaseRequestDetailDO detailDO1 = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(billId, materialsNo, detailDO.getRowNo());
            if (null == detailDO1) {
                code = purchaseRequestDetailMapper.insert(detailDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
                if (code != ErrorCode.Success) {
                    return code;
                }
            } else {
                PurchaseRequestDetailDO updateDetailDO = new PurchaseRequestDetailDO();
                updateDetailDO.setBillId(billId);
                updateDetailDO.setMaterialsNo(materialsNo);
                updateDetailDO.setRowNo(detailDO.getRowNo());
                updateDetailDO.setQty(detailDO.getQty());
                updateDetailDO.setNetPrice(detail.getNetPrice());
                updateDetailDO.setDeliveryDate(detail.getDeliveryDate());
                updateDetailDO.setSettlementPrice(detail.getSettlementPrice());
                updateDetailDO.setApplyTotalPrice(detail.getApplyTotalPrice());
                updateDetailDO.setPriceSchemeId(detail.getPriceSchemeId());
                updateDetailDO.setPriceSchemeName(detail.getPriceSchemeName());
                if (StringUtils.equals("1", isReplaceMaterial)) {
                    updateDetailDO.setMaterialsNo(detailDO.getMaterialsNo());
                    updateDetailDO.setOriginalMaterialsNo(detailDO.getOriginalMaterialsNo());
                    updateDetailDO.setUnit(detailDO.getUnit());
                    updateDetailDO.setMaterialsDes(detailDO.getMaterialsDes());
                    updateDetailDO.setPrice(detailDO.getPrice());
                    updateDetailDO.setSettlementPrice(detailDO.getSettlementPrice());
                    updateDetailDO.setApplyTotalPrice(detailDO.getApplyTotalPrice());
                    code = purchaseRequestDetailMapper.updateByOriginalMaterial(updateDetailDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;

                    //更新上游的销售订单
                    //根据采购订单查找销售订单
                    String purchaseContractNo = purchaseRequestVO.getPurchaseContractNo();
                    if (StringUtils.isNotBlank(purchaseContractNo)) {
                        SaleIntentionDO saleIntentionDO = saleIntentionMapper.itemBySaleNo(purchaseContractNo);
                        if (saleIntentionDO != null) {
                            //获取销售订单明细
                            List<SaleIntentionDetailDO> saleIntentionDetailDOS = saleIntentionDetailMapper.list(saleIntentionDO.getId());
                            BigDecimal detailPrice = updateDetailDO.getPrice();
                            if (detailPrice == null) {
                                detailPrice = BigDecimal.ZERO;
                            }
                            for (SaleIntentionDetailDO saleIntentionDetailDO : saleIntentionDetailDOS) {
                                if (StringUtils.equals(saleIntentionDetailDO.getMaterialsNo(), detailDO.getOriginalMaterialsNo())) {
                                    saleIntentionDetailDO.setOriginalMaterialsNo(detailDO.getOriginalMaterialsNo());
                                    saleIntentionDetailDO.setMaterialsNo(detailDO.getMaterialsNo());
                                    saleIntentionDetailDO.setMaterialsDes(detailDO.getMaterialsDes());
                                    saleIntentionDetailDO.setPrice(detailPrice);
                                    saleIntentionDetailDO.setUnit(detailDO.getUnit());
                                    saleIntentionDetailDO.setApplyTotalPrice(detailPrice.multiply(saleIntentionDetailDO.getQty()));
                                    saleIntentionDetailDO.setUnitPriceAfterAdjust(detailDO.getSettlementPrice());
                                    saleIntentionDetailDO.setTotalPriceAfterAdjust(saleIntentionDetailDO.getUnitPriceAfterAdjust().multiply(saleIntentionDetailDO.getQty()));
                                    saleIntentionDetailMapper.update(saleIntentionDetailDO);
                                }
                            }

                            //计算销售订单总金额
                            BigDecimal totalPrice = BigDecimal.ZERO;
                            BigDecimal discountPrice = BigDecimal.ZERO;
                            for (SaleIntentionDetailDO saleIntentionDetailDO : saleIntentionDetailDOS) {
                                totalPrice = totalPrice.add(saleIntentionDetailDO.getPrice().multiply(saleIntentionDetailDO.getQty()));
                                discountPrice = discountPrice.add(saleIntentionDetailDO.getUnitPriceAfterAdjust().multiply(saleIntentionDetailDO.getQty()));
                            }
                            saleIntentionDO.setTotalSettlementPrice(totalPrice);
                            saleIntentionDO.setTotalDiscountPrice(discountPrice);

                            saleIntentionMapper.update(saleIntentionDO);
                        }
                    }
                } else {
                    code = purchaseRequestDetailMapper.update(updateDetailDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
                }
                if (code != ErrorCode.Success) {
                    return code;
                }
            }
        }

        if (!CollectionUtils.isEmpty(detailDOS)) {
            for (PurchaseRequestDetailDO sidDO : detailDOS) {
                if (sidDO.getSendQty().compareTo(new BigDecimal(0)) != 0) {
                    return ErrorCode.AdjustCannotDelete;
                }
                if (purchaseRequestDetailMapper.deleteByBillIdMaterialsNo(sidDO.getBillId(), sidDO.getMaterialsNo(), sidDO.getRowNo()) <= 0) {
                    return ErrorCode.AdjustDeleteError;
                }
            }
        }

        PurchaseRequestDO updatePurchaseRequestDO = new PurchaseRequestDO();
        updatePurchaseRequestDO.setBillId(purchaseRequestVO.getBillId());
        updatePurchaseRequestDO.setTotalValue(totalValue);
        updatePurchaseRequestDO.setSettlementValue(totalValue);
        updatePurchaseRequestDO.setReceiverName(purchaseRequestVO.getReceiverName());
        updatePurchaseRequestDO.setReceiverAddress(purchaseRequestVO.getReceiverAddress());
        updatePurchaseRequestDO.setReceiverFax(purchaseRequestVO.getReceiverFax());
        updatePurchaseRequestDO.setReceiverTel(purchaseRequestVO.getReceiverTel());
        updatePurchaseRequestDO.setUpdateId(purchaseRequestVO.getUpdateId());
        updatePurchaseRequestDO.setUpdateDate(new Date());
        updatePurchaseRequestDO.setUpdateName(purchaseRequestVO.getUpdateName());
        updatePurchaseRequestDO.setRemark(purchaseRequestVO.getRemark());
        return purchaseRequestMapper.updateShipInfo(updatePurchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode auditBill(PurchaseRequestVO purchaseRequestVO, String orgId, String userId) throws Exception {
        if (purchaseRequestVO.getBillId() == null || purchaseRequestVO.getBillId() == "") {
            return ErrorCode.PurchaseBillIdNotExists;
        }
        //保存備注信息
        saveDetailsRemark(purchaseRequestVO);
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(purchaseRequestVO.getBillId());
        if (purchaseRequestDO == null) {
            return ErrorCode.PurchaseInfoNotExists;
        }
        if (!purchaseRequestDO.getBillStatus().equals(PurchaseStatus.WaitAudit.toString()) && !purchaseRequestDO.getBillStatus().equals(PurchaseStatus.RefusedSumbit.toString())) {
            return ErrorCode.PurchaseStatusNotAudit;
        }
        DataDictionaryDO auditDataDictionaryDO = dataDictionaryMapper.itemByCode(PurchaseStatus.Name.toString(), purchaseRequestVO.getBillStatus());
        if (auditDataDictionaryDO != null) {
            purchaseRequestDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        purchaseRequestDO.setRemark(purchaseRequestVO.getRemark());
        purchaseRequestDO.setBillStatus(purchaseRequestVO.getBillStatus());
        purchaseRequestDO.setAuditDate(new Date());
        purchaseRequestDO.setAuditId(purchaseRequestVO.getAuditId());
        purchaseRequestDO.setAuditMessage(purchaseRequestVO.getAuditMessage());
        // 允许修改收货相关信息
        purchaseRequestDO.setReceiverName(purchaseRequestVO.getReceiverName());
        purchaseRequestDO.setReceiverAddress(purchaseRequestVO.getReceiverAddress());
        purchaseRequestDO.setReceiverTel(purchaseRequestVO.getReceiverTel());
        purchaseRequestDO.setReceiverFax(purchaseRequestVO.getReceiverFax());

        if (StringUtils.isNotEmpty(purchaseRequestVO.getSendCompanyCode())) {
            purchaseRequestDO.setSendCompanyCode(purchaseRequestVO.getSendCompanyCode());
        }
        if (StringUtils.isNotEmpty(purchaseRequestVO.getSendCompanyName())) {
            purchaseRequestDO.setSendCompanyName(purchaseRequestVO.getSendCompanyName());
        }

        ActionResult userAuth = authClient.getUserDetail(purchaseRequestDO.getAuditId());
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        if (userInfo != null) {
            purchaseRequestDO.setAuditName(userInfo.getName());
        }
        String message = "";
        if (purchaseRequestDO.getBillStatus().equals(PurchaseStatus.AuditPass.toString())) {
            createNewRequest(purchaseRequestDO.getBillId(), orgId, userId, purchaseRequestVO);
            message = "[审核通过]" + (purchaseRequestDO.getAuditMessage() == null ? "" : purchaseRequestDO.getAuditMessage());
        } else {
            message = "[审核拒绝]" + purchaseRequestDO.getAuditMessage();
        }
        insetLog(purchaseRequestDO.getAuditName(), purchaseRequestDO.getAuditId(), message, purchaseRequestDO);

        BigDecimal totalValue = updateMaterialsSourceQty(purchaseRequestVO.getMaterialsList());
        purchaseRequestDO.setTotalValue(totalValue);
        purchaseRequestDO.setSettlementValue(totalValue);

        return purchaseRequestMapper.update(purchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    /**
     * 保存详情中的備注信息
     *
     * @param vo
     */
    private void saveDetailsRemark(PurchaseRequestVO vo) {
        if (CollectionUtils.isEmpty(vo.getMaterialsList()) || null == vo.getBillId()) {
            return;
        }
        for (PurchaseRequestDetailVO v : vo.getMaterialsList()) {
            if (StringUtils.isBlank(v.getMaterialsNo())) {
                throw new CommonBusiExceptions("参数异常：零件号为必须参数");
            }
            v.setBillId(vo.getBillId());
            PurchaseRequestDetailDO m = BeanUtil.do2bo(v, PurchaseRequestDetailDO.class);
            purchaseRequestDetailMapper.updateRemark(m);
        }
    }

    private void createNewRequest(String billId, String orgId, String userId, PurchaseRequestVO requestVO) throws Exception {
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(billId);
        if (Integer.valueOf(1).equals(purchaseRequestDO.getIsDirectCast()) && !orgId.equals(purchaseRequestDO.getSoldOrgId())) {
            List<PurchaseRequestDetailDO> detailDOs = purchaseRequestDetailMapper.list(billId);
            List<PurchaseRequestDetailVO> detailVOs = new ArrayList<PurchaseRequestDetailVO>();
            CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), purchaseRequestDO.getSoldOrgId());
            for (PurchaseRequestDetailDO detailDO : detailDOs) {
                PurchaseRequestDetailVO detailVO = convertVO(detailDO);
                if (companySupplierDO != null) {
                    detailVO.setPriceSchemeId(null);
                    detailVO.setPriceSchemeName(null);
                }
                PriMaterialsDO materialsDO = priMaterialsMapper.getInfoByMaterialsNo(detailVO.getMaterialsNo(), purchaseRequestDO.getSoldOrgId());
                if (materialsDO == null) {
                    detailVO.setSourcePrice(detailVO.getSettlementPrice());
                    detailVO.setPrice(BigDecimal.ZERO);
                    detailVO.setSettlementPrice(detailVO.getPrice());
                    detailVO.setApplyTotalPrice(BigDecimal.ZERO);
                } else {
                    detailVO.setSourcePrice(detailVO.getSettlementPrice());
                    detailVO.setPrice(materialsDO.getPrice() == null ? BigDecimal.ZERO : (materialsDO.getPrice().divide(new BigDecimal(100))));
                    detailVO.setSettlementPrice(detailVO.getPrice());
                    detailVO.setApplyTotalPrice(materialsDO.getPrice().multiply(detailVO.getQty()));
                }
                detailVOs.add(detailVO);
            }
            PurchaseRequestVO purchaseRequestVO = new PurchaseRequestVO();
            BeanUtils.copyProperties(purchaseRequestDO, purchaseRequestVO);
            purchaseRequestVO.setBillId(null);
            if (requestVO.getDispatcherId() != null) {
                purchaseRequestVO.setDispatcherId(requestVO.getDispatcherId());
            }
            if (requestVO.getDispatcherName() != null) {
                purchaseRequestVO.setDispatcherName(requestVO.getDispatcherName());
            }
            purchaseRequestVO.setBillNo(purchaseRequestDO.getBillNo());
            purchaseRequestVO.setPurchaseOrgId(purchaseRequestDO.getSupplierOrgId());
            purchaseRequestVO.setPurchaseOrgName(purchaseRequestDO.getSupplierOrgName());
            purchaseRequestVO.setSupplierOrgId(purchaseRequestDO.getSoldOrgId());
            purchaseRequestVO.setSupplierOrgName(purchaseRequestDO.getSoldOrgName());
            //CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), purchaseRequestDO.getSoldOrgId());
            if (companySupplierDO != null) {
                purchaseRequestVO.setSupplierOrgName(companySupplierDO.getCompanyName());
            }
            purchaseRequestVO.setDirectSourceId(purchaseRequestDO.getBillId());
            purchaseRequestVO.setDirectSourceOrder(purchaseRequestDO.getBillNo());
            purchaseRequestVO.setAuditId(null);
            purchaseRequestVO.setAuditName(null);
            purchaseRequestVO.setAuditDate(null);
            purchaseRequestVO.setAuditMessage(null);
            purchaseRequestVO.setBillStatus(PurchaseRequestBillStatusEnum.SUBMITED.getStatus());
            purchaseRequestVO.setMaterialsList(detailVOs);
            purchaseRequestVO.setCreateOrgId(orgId);
            purchaseRequestVO.setCreateId(userId);
            purchaseRequestVO.setSeller(false);
            purchaseRequestVO.setTotalValue(purchaseRequestDO.getTotalValue() == null ? null : (purchaseRequestDO.getTotalValue().divide(new BigDecimal(100))));
            purchaseRequestVO.setSettlementValue(purchaseRequestDO.getSettlementValue() == null ? null : (purchaseRequestDO.getSettlementValue().divide(new BigDecimal(100))));
            purchaseRequestVO.setDeptCode(requestVO.getDeptCode());
            purchaseRequestVO.setDeptName(requestVO.getDeptName());
            purchaseRequestVO.setPurchaseCode(requestVO.getPurchaseCode());
            purchaseRequestVO.setPurchaseName(requestVO.getPurchaseName());
            insert(purchaseRequestVO, orgId, "submit", "auto");
        }

        //如果发货公司是云内，则同步ERP
//        if (orgId.equals(purchaseRequestDO.getSoldOrgId())) {
//            CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
//            if ("1".equals(companyInfoDO.getCompanyType())) {
//                syncOrder(billId);
//            }
//        }
    }

    private PurchaseRequestDetailVO convertVO(PurchaseRequestDetailDO detailDO) {
        PurchaseRequestDetailVO detailVO = new PurchaseRequestDetailVO();
        BeanUtils.copyProperties(detailDO, detailVO);
        detailVO.setSourcePrice(detailDO.getSettlementPrice() == null ? null : (detailDO.getSettlementPrice().divide(new BigDecimal(100))));
        detailVO.setPrice(detailDO.getPrice() == null ? null : (detailDO.getPrice().divide(new BigDecimal(100))));
        detailVO.setSettlementPrice(detailDO.getSettlementPrice() == null ? null : (detailDO.getSettlementPrice().divide(new BigDecimal(100))));
        detailVO.setApplyTotalPrice(detailDO.getApplyTotalPrice() == null ? null : (detailDO.getApplyTotalPrice().divide(new BigDecimal(100))));
        return detailVO;
    }

    /**
     * 同步订单
     *
     * @throws Exception
     */
//    public void syncOrder(String billId) throws Exception {
//        if ("1".equals(syncFlag)) {
//            OrderVO orderVO = new OrderVO();
//            OrderHeaderVO orderHeaderVO = getOrderHeaderVO(billId);
//            List<OrderDetailVO> orderDetailVOs = getOrderDetailVOs(billId);
//            orderVO.setHeader(orderHeaderVO);
//            orderVO.setDetails(orderDetailVOs);
//            ActionResult result = erpSyncClient.syncOrder(orderVO);
//            if (ErrorCode.Success.getCode() != result.getCode()) {
//                throw new Exception(result.getMessage());
//            }
//        }
//    }

//    private OrderHeaderVO getOrderHeaderVO(String billId) throws Exception {
//        DateFormat format = new SimpleDateFormat("yyyyMMdd");
//        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(billId);
//        OrderHeaderVO orderHeaderVO = new OrderHeaderVO();
//        orderHeaderVO.setGysDdId(billId);
//        orderHeaderVO.setGysDdCode(purchaseRequestDO.getBillNo());
//        //云内 20221129--原来的值是默认1001
//        orderHeaderVO.setGysDdXsgsId(purchaseRequestDO.getSalesCode());
//        orderHeaderVO.setGysDdKhgsId(getErpCode(purchaseRequestDO.getPurchaseOrgId()));
//        orderHeaderVO.setGysDdShr(purchaseRequestDO.getReceiverName());
//        orderHeaderVO.setGysDdShdh(purchaseRequestDO.getReceiverTel());
//        orderHeaderVO.setGysDdShdz(purchaseRequestDO.getReceiverAddress());
//        orderHeaderVO.setGysDdJhrq(purchaseRequestDO.getDeliveryDate() == null ? null : format.format(purchaseRequestDO.getDeliveryDate()));
//        orderHeaderVO.setGysDdZdr(purchaseRequestDO.getCreateName());
//        orderHeaderVO.setGysDdZdrq(purchaseRequestDO.getCreateDate() == null ? null : format.format(purchaseRequestDO.getCreateDate()));
//        orderHeaderVO.setGysDdNote(purchaseRequestDO.getRemark());
//        orderHeaderVO.setGysDdFcgs(purchaseRequestDO.getSendCompanyCode());
//        orderHeaderVO.setBillType(Integer.valueOf(1).equals(purchaseRequestDO.getIsDirectCast()) ? "3" : "1");
//        orderHeaderVO.setTransType(purchaseRequestDO.getShippingMethod());
//        orderHeaderVO.setPreCheckDate(purchaseRequestDO.getAuditDate() == null ? null : format.format(purchaseRequestDO.getAuditDate()));
//        orderHeaderVO.setLastChgDate(purchaseRequestDO.getUpdateDate() == null ? null : format.format(purchaseRequestDO.getUpdateDate()));
//        orderHeaderVO.setLastChgName(purchaseRequestDO.getUpdateName());
//        orderHeaderVO.setIsRead("0");
//        orderHeaderVO.setReceiveTime(null);
//        orderHeaderVO.setErpImportTime(null);
//        orderHeaderVO.setApprover(purchaseRequestDO.getAuditName());
//        if (StringUtils.isNotEmpty(purchaseRequestDO.getDispatcherId())) {
//            ProfileDO profileDO = profileMapper.itemById(purchaseRequestDO.getDispatcherId());
//            if (profileDO != null && companyUtil.ynOrgId().equals(profileDO.getSpaceId())) {
//                if (StringUtils.isNotEmpty(profileDO.getSapCode())) {
//                    if (profileDO.getSapCode().length() < 8) {
//                        orderHeaderVO.setSalesCode(profileDO.getSapCode() + "6");
//                    } else {
//                        orderHeaderVO.setSalesCode(profileDO.getSapCode());
//                    }
//                }
//            } else {
//                orderHeaderVO.setSalesCode(profileDO.getSapCode());
//            }
//            orderHeaderVO.setSalesName(profileDO.getName());
//        }
//        return orderHeaderVO;
//    }
    private String getErpCode(String orgId) throws Exception {
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByPlatOrgId(orgId);
        if (companyDealerDO == null) {
            throw new Exception("关系公司不存在");
        }
        return companyDealerDO.getDealerCode();
    }

//    private List<OrderDetailVO> getOrderDetailVOs(String billId) {
//        List<PurchaseRequestDetailDO> detailVOs = purchaseRequestDetailMapper.list(billId);
//        List<OrderDetailVO> orderDetailVOs = new ArrayList<OrderDetailVO>();
//        for (PurchaseRequestDetailDO purchaseRequestDetailDO : detailVOs) {
//            OrderDetailVO orderDetailVO = new OrderDetailVO();
//            orderDetailVO.setGysDdId(billId);
//            orderDetailVO.setGysDdItemId(purchaseRequestDetailDO.getBillId() + "-" + purchaseRequestDetailDO.getMaterialsNo());
//            orderDetailVO.setGysDdHsdj(purchaseRequestDetailDO.getPrice() == null ? BigDecimal.ZERO : (purchaseRequestDetailDO.getPrice().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP)));
//            orderDetailVO.setGysDdHsje(purchaseRequestDetailDO.getApplyTotalPrice() == null ? BigDecimal.ZERO : (purchaseRequestDetailDO.getApplyTotalPrice().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP)));
//            orderDetailVO.setYxddSqmxBz(purchaseRequestDetailDO.getRemark());
//            orderDetailVO.setRownb(purchaseRequestDetailDO.getRowNo() == null ? null : new BigDecimal(purchaseRequestDetailDO.getRowNo()));
//            orderDetailVO.setGysDdSl(purchaseRequestDetailDO.getQty());
//            orderDetailVO.setGysDdMaterialId(purchaseRequestDetailDO.getMaterialsId());
//            orderDetailVO.setRemark(purchaseRequestDetailDO.getRemark());
//            orderDetailVO.setWlssgs(purchaseRequestDetailDO.getMadeCompanyCode());
//            orderDetailVOs.add(orderDetailVO);
//        }
//        return orderDetailVOs;
//    }


    /**
     * 更新零件来源的数量信息
     */
    private BigDecimal updateMaterialsSourceQty(List<PurchaseRequestDetailVO> purchaseRequestDetailVOS) {
        if (ListUtil.isNullOrEmpty(purchaseRequestDetailVOS)) {
            return BigDecimal.ZERO;
        }
        PurchaseRequestDetailDO purchaseRequestDetailDO = null;
        BigDecimal totalValue = BigDecimal.ZERO;
        for (PurchaseRequestDetailVO purchaseRequestDetailVO : purchaseRequestDetailVOS) {
            purchaseRequestDetailDO = new PurchaseRequestDetailDO();
            purchaseRequestDetailDO.setBillId(purchaseRequestDetailVO.getBillId());
            purchaseRequestDetailDO.setRowNo(purchaseRequestDetailVO.getRowNo());
            purchaseRequestDetailDO.setMaterialsNo(purchaseRequestDetailVO.getMaterialsNo());

            purchaseRequestDetailDO
                    .setInventoryProvideQty(purchaseRequestDetailVO.getInventoryProvideQty());
            purchaseRequestDetailDO
                    .setAgentProvideQty(purchaseRequestDetailVO.getAgentProvideQty());
            purchaseRequestDetailDO.setBuyerDealQty(purchaseRequestDetailVO.getBuyerDealQty());

            //更新价格方案和价格
            purchaseRequestDetailDO.setSettlementPrice(purchaseRequestDetailVO.getSettlementPrice().multiply(new BigDecimal("100")));
            purchaseRequestDetailDO.setPrice(purchaseRequestDetailVO.getPrice().multiply(new BigDecimal("100")));
//            前端都已经算好了，不管是否加价，都按照前端穿过来的值更新
//            if (IS_RAISE_YES.equals(purchaseRequestDetailVO.getIsRaise())) {
//                purchaseRequestDetailDO.setSettlementPrice((purchaseRequestDetailDO.getPrice().multiply(new BigDecimal("1.05"))));
//            }
            purchaseRequestDetailDO.setIsRaise(purchaseRequestDetailVO.getIsRaise());
            BigDecimal qty = purchaseRequestDetailVO.getQty();
            BigDecimal amont = BigDecimal.valueOf(purchaseRequestDetailDO.getSettlementPrice().multiply(qty).doubleValue());
            totalValue = totalValue.add(amont);
            purchaseRequestDetailDO.setApplyTotalPrice(amont);

            purchaseRequestDetailDO.setPriceSchemeId(purchaseRequestDetailVO.getPriceSchemeId());
            purchaseRequestDetailDO.setPriceSchemeName(purchaseRequestDetailVO.getPriceSchemeName());
            purchaseRequestDetailMapper.update(purchaseRequestDetailDO);
        }
        return totalValue;
    }

    public ErrorCode cancel(PurchaseRequestVO purchaseRequestVO) throws Exception {
        if (StringUtil.isNullOrEmpty(purchaseRequestVO.getBillId())) {
            return ErrorCode.PurchaseBillIdNotExists;
        }
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(purchaseRequestVO.getBillId());
        if (purchaseRequestDO == null) {
            return ErrorCode.PurchaseInfoNotExists;
        }
        if (!purchaseRequestDO.getBillStatus().equals(PurchaseStatus.WaitAudit.toString())) {
            throw new Exception("只有待审核的采购订单才能撤销");
        }
        purchaseRequestDO.setBillStatus(PurchaseStatus.Saved.toString());
        DataDictionaryDO auditDataDictionaryDO = dataDictionaryMapper.itemByCode(PurchaseStatus.Name.toString(), PurchaseStatus.Saved.toString());
        if (auditDataDictionaryDO != null) {
            purchaseRequestDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        return purchaseRequestMapper.update(purchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode remove(PurchaseRequestVO purchaseRequestVO) {
        if (purchaseRequestVO.getBillId() == null || purchaseRequestVO.getBillId() == "") {
            return ErrorCode.PurchaseBillIdNotExists;
        }
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(purchaseRequestVO.getBillId());
        if (purchaseRequestDO == null) {
            return ErrorCode.PurchaseInfoNotExists;
        }
        int num = purchaseInboundMapper.findNumByRequestOrder(purchaseRequestDO.getBillNo(), purchaseRequestDO.getPurchaseOrgId());
        if (num > 0) {
            return ErrorCode.PurchaseInboundExists;
        }
        SaleIntentionDO saleIntentionDO = saleIntentionMapper.itemByPurchaseNo(purchaseRequestDO.getBillNo(), purchaseRequestDO.getSupplierOrgId());
        if (saleIntentionDO != null) {
            return ErrorCode.PurchaseSaleIntentionExists;
        }
        PurchaseRequestVO record = new PurchaseRequestVO();
        record.setDirectSourceOrder(purchaseRequestDO.getBillNo());
        record.setPurchaseOrgId(purchaseRequestDO.getSupplierOrgId());
        if (!ListUtil.isNullOrEmpty(purchaseRequestMapper.list(record))) {
            return ErrorCode.PurchaseSaleExists;
        }

        BuyPlanDO buyPlanDO = buyPlanMapper.findByPlanOrder(purchaseRequestDO.getBuyPlanOrder(), purchaseRequestDO.getPurchaseOrgId());
        if (buyPlanDO != null) {
            // start    更新对应采购计划详情中的isgenerate字段为未生成采购单（根据planId+零件编码匹配更新）,add by wangzhaoyu 20200817 刘媛媛提出删除采购单后需要能再次选择采购计划
            rollbackPlanDetailGenerate(purchaseRequestDO, buyPlanDO);
            //end

            //获取现在数据库中的采购计划详情，判断采购计划创建订单的状态
            List<BuyPlanDetailDO> list = buyPlanDetailMapper.list(buyPlanDO.getId());
//            int sendStatus = buyPlanDetailMapper.findSendStatus(buyPlanDO.getId());
            //需求：创建采购订单的时候如果所有未结单的零件都创建了采购订单则需要把采购计划的创建状态改为已创建（send_status=2）,如果部分创建则为部分创建
            //判断逻辑：1.如果创建了采购订单的零件行数+没有创建订单且接单的额零件行数=总行数（赋值全部创建）
            //2.否则如果创建了采购订单的零件行数为0则赋值为未创建
            //3.其他情况均为部分创建
            int allDetailNum = 0;//计划所有零件行数
            int generateNum = 0;//创建了采购订单的零件行数
            int noGeneManualFinish = 0;//没有创建订单且接单的额零件行数
            for (BuyPlanDetailDO detailDO : list) {
                allDetailNum++;
                Integer isGenerate = detailDO.getIsGenerate();
                String finishState = detailDO.getFinishState();
                if (isGenerate != null && isGenerate.equals(1)) {
                    generateNum++;
                } else if (!StringUtils.isEmpty(finishState) && "1".equals(finishState)) {
                    noGeneManualFinish++;
                }
            }
            Integer sendStatus = null;
            if (generateNum + noGeneManualFinish - allDetailNum == 0) {
                sendStatus = 2;
            } else if (generateNum == 0) {
                sendStatus = 0;
            } else {
                sendStatus = 1;
            }
            buyPlanMapper.updateSendStatus(purchaseRequestDO.getBuyPlanOrder(), sendStatus, purchaseRequestDO.getPurchaseOrgId());
        }
        if (purchaseRequestDO.getIsSale() == 0) {
            purchaseRequestDO.setDel(true);
            purchaseRequestDO.setUpdateDate(new Date());
            ErrorCode code = purchaseRequestMapper.update(purchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
            if (code.getCode() == 0 && !StringUtil.isNullOrEmpty(purchaseRequestDO.getDirectSourceOrder())) {
                PurchaseRequestDO purDO = purchaseRequestMapper.itemByBillNo(purchaseRequestDO.getDirectSourceOrder());
                if (purDO != null) {
                    purchaseRequestMapper.updateDirectAddEnable(purDO.getBillId(), 0);
                }
            }
            return code;
        }

        if (!purchaseRequestDO.getBillStatus().equals(PurchaseStatus.Saved.toString()) && !purchaseRequestDO.getBillStatus().equals(PurchaseStatus.AuditRefused.toString())) {
            return ErrorCode.PurchaseStatusNotUpdate;
        }
        purchaseRequestDO.setDel(true);
        purchaseRequestDO.setUpdateDate(new Date());

        releaseAgentPlan(purchaseRequestDO.getBuyPlanOrder(), purchaseRequestDO.getPurchaseOrgId());
        ErrorCode code = purchaseRequestMapper.update(purchaseRequestDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;

        //直投采购单，删除时候释放来源订单
        if (code.getCode() == 0 && !StringUtil.isNullOrEmpty(purchaseRequestDO.getDirectSourceOrder())) {
            PurchaseRequestDO purDO = purchaseRequestMapper.itemByBillNo(purchaseRequestDO.getDirectSourceOrder());
            if (purDO != null) {
                purchaseRequestMapper.updateDirectAddEnable(purDO.getBillId(), 0);
            }
        }
        return code;
    }

    /**
     * 删除采购单的时候,把采购计划PlanDetial中对应的generate字段更新为0,表示未创建采购单
     *
     * @param purchaseRequestDO
     * @param buyPlanDO
     */
    private void rollbackPlanDetailGenerate(PurchaseRequestDO purchaseRequestDO, BuyPlanDO buyPlanDO) {
        if (purchaseRequestDO == null || buyPlanDO == null) {
            return;
        }
        String billId = purchaseRequestDO.getBillId();
        if (StringUtils.isEmpty(billId)) {
            return;
        }
        List<PurchaseRequestDetailDO> purRequestDetails = purchaseRequestDetailMapper.list(billId);

        //遍历所有零件编码，更新零件编码对应采购计划中的generate字段值
        for (PurchaseRequestDetailDO detailDO : purRequestDetails) {
            String materialsNo = detailDO.getMaterialsNo();
            if (StringUtils.isEmpty(materialsNo)) {
                continue;
            }
            buyPlanDetailMapper.robackRenerate2Zero(buyPlanDO.getId(), materialsNo);
        }
    }

    /**
     * 如果是代理商采购计划转的订单，删除时顺便释放掉原采购计划
     *
     * @param planNo
     * @param orgId
     */
    private void releaseAgentPlan(String planNo, String orgId) {
        if (StringUtils.isBlank(planNo)) {
            return;
        }
        AgentPlanDO agentPlan = agentPlanMapper.getByPlanNo(planNo, orgId);
        if (null == agentPlan) {
            return;
        }
        agentPlan.setGenPurFlag(GEN_ORDER_FLAG_NO);
        agentPlanMapper.update(agentPlan);
    }

    public PurchaseRequestVO itemByNo(String billNo, Integer isDirect, String orgId) throws Exception {
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByBillNo(billNo);
        if (purchaseRequestDO == null) {
            return null;
        }
        purchaseRequestDO.setTotalValue(purchaseRequestDO.getTotalValue().divide(new BigDecimal("100")));
        purchaseRequestDO.setSettlementValue(purchaseRequestDO.getSettlementValue().divide(new BigDecimal("100")));
        PurchaseRequestVO purchaseRequestVO = getVO(purchaseRequestDO, orgId);
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(purchaseRequestDO.getSupplierOrgId());
        if (companyInfoDO != null) {
            purchaseRequestVO.setPlatCompany(true);
            purchaseRequestVO.setIsUrgentPrice(companyInfoDO.getIsUrgentPrice());
        } else {
            purchaseRequestVO.setPlatCompany(false);
        }
        List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(purchaseRequestDO.getBillId());
        List<PurchaseRequestDetailVO> detailVOList = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;
        CompanyInfoDO companyItem = companyInfoMapper.item(orgId);
        Integer isSap = companyItem.getIsSap();
        String companyType = companyItem.getCompanyType();
        for (PurchaseRequestDetailDO detailDO : detailDOList) {
            BigDecimal sourcePrice = detailDO.getSettlementPrice();
            if (isDirect != null && isDirect == 1) {
                PriMaterialsDO materialsDO = priMaterialsMapper.itemByNo(detailDO.getMaterialsNo(), purchaseRequestDO.getSupplierOrgId());
                if (materialsDO != null) {
                    detailDO.setPrice(materialsDO.getStandardPrice() == null ? BigDecimal.ZERO : materialsDO.getStandardPrice());
                    detailDO.setSettlementPrice(detailDO.getPrice());
                    detailDO.setApplyTotalPrice(detailDO.getQty().multiply(detailDO.getPrice()));
                    totalPrice = totalPrice.add(detailDO.getApplyTotalPrice());
                }
            }
            detailDO.setSettlementPrice(detailDO.getSettlementPrice().divide(new BigDecimal("100")));
            detailDO.setPrice(detailDO.getPrice().divide(new BigDecimal("100")));
            detailDO.setApplyTotalPrice(detailDO.getApplyTotalPrice().divide(new BigDecimal("100")));
            PurchaseRequestDetailVO purchaseRequestDetailVO = getDetailVO(detailDO);
            purchaseRequestDetailVO.setSourcePrice(sourcePrice);
            //查询购买量
            MaterialsVO materialsVO = priMaterialsMapper.selectMinimumBuy(purchaseRequestDO.getSupplierOrgId(), detailDO.getMaterialsNo());
            if (materialsVO != null) {
                purchaseRequestDetailVO.setIsMinimumBuy(materialsVO.getIsMinimumBuy());
                purchaseRequestDetailVO.setMinimumBuy(materialsVO.getMinimumBuy());
            }
            EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum(detailDO.getMaterialsNo(), purchaseRequestDO.getSupplierOrgId(), null);
            if (enableAndOccupyVO != null) {
                purchaseRequestDetailVO.setIntentionNum(enableAndOccupyVO.getIntentionNum());
                purchaseRequestDetailVO.setDeliveryNum(enableAndOccupyVO.getDeliveryNum());
                purchaseRequestDetailVO.setEnableNum(enableAndOccupyVO.getEnableNum());
            }
            if (purchaseRequestDO.getPurchaseOrgId() == null) {
                throw new Exception("单据信息不完整（purchaseOrgId不能为空）");
            }
            List<MarketingActivityPriceVO> MarketingActivityDOList = marketingActivityService.activityPriceList(purchaseRequestDO.getPurchaseOrgId(), purchaseRequestDO.getSupplierOrgId(), detailDO.getMaterialsNo());
            purchaseRequestDetailVO.setMarketingActivityPriceVOList(MarketingActivityDOList);

            //判断是否是代理商
            if (null != isSap && 0 == isSap && companyType != null && "2".equals(companyType)) {
                //获取交货日期
                Date deliveryDate = saleIntentionDetailMapper.getDeliveryDate(detailDO.getMaterialsNo(), detailDO.getBillId());
                purchaseRequestDetailVO.setDeliveryDate(deliveryDate);
            }
            detailVOList.add(purchaseRequestDetailVO);
        }
        if (isDirect != null && isDirect == 1) {
            totalPrice = totalPrice.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            purchaseRequestVO.setTotalValue(totalPrice);
            purchaseRequestVO.setSettlementValue(totalPrice);
        }
        purchaseRequestVO.setMaterialsList(detailVOList);
        purchaseRequestVO.setLogDOList(purchaseRequestLogMapper.listBybillId(purchaseRequestDO.getBillId()));
        return purchaseRequestVO;
    }

    public PurchaseRequestVO item(String billId, Integer isDirect, String orgId) throws Exception {
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(billId);
        if (purchaseRequestDO == null) {
            return null;
        }
        purchaseRequestDO.setTotalValue(purchaseRequestDO.getTotalValue().divide(new BigDecimal("100")));
        purchaseRequestDO.setSettlementValue(purchaseRequestDO.getSettlementValue().divide(new BigDecimal("100")));
        PurchaseRequestVO purchaseRequestVO = getVO(purchaseRequestDO, orgId);
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(purchaseRequestDO.getSupplierOrgId());
        if (companyInfoDO != null) {
            purchaseRequestVO.setPlatCompany(true);
            purchaseRequestVO.setIsUrgentPrice(companyInfoDO.getIsUrgentPrice());
        } else {
            purchaseRequestVO.setPlatCompany(false);
        }
        List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(billId);
        List<PurchaseRequestDetailVO> detailVOList = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;
        CompanyInfoDO companyItem = companyInfoMapper.item(orgId);
        Integer isSap = companyItem.getIsSap();
        String companyType = companyItem.getCompanyType();

        List<BillStockDO> billStockDOs = getStockInfo(purchaseRequestVO.getIsDirectCast(), purchaseRequestVO.getSoldOrgId(), purchaseRequestVO.getBillNo());
        Map<String, BigDecimal> stockMap = new HashMap<String, BigDecimal>();
        if (CollectionUtils.isNotEmpty(billStockDOs)) {
            for (BillStockDO billStockDO : billStockDOs) {
                stockMap.put(billStockDO.getMaterialCode(), billStockDO.getQuantity());
            }
        }
//        Map<String, MaterialVO> replaceMaterialsMap = queryReplaceMaterialsMap(detailDOList);
//
//        Map<String, DlsddfpmxbDto> dlsddfpmxbDtoMap = queryFpdDetailsMapByBillNo(purchaseRequestDO.getBillNo());
//        if (MapUtils.isNotEmpty(dlsddfpmxbDtoMap)) {
//            purchaseRequestVO.setHasInvoice(1);
//        } else {
//            purchaseRequestVO.setHasInvoice(0);
//        }
        List<String> materialsNos = detailDOList.stream().filter(x -> StringUtils.isNotBlank(x.getMaterialsNo())).map(x -> x.getMaterialsNo()).collect(Collectors.toList());
        //库存的orgId
        String inventoryOrgId = purchaseRequestDO.getSupplierOrgId();
        if (purchaseRequestDO.getIsDirectCast() != null && purchaseRequestDO.getIsDirectCast() == 1) {
            inventoryOrgId = purchaseRequestDO.getSoldOrgId();
        }
        Map<String, BigDecimal> ynInventoryMap = marketingActivityService.queryYnInventoryMapByMaterials(materialsNos, inventoryOrgId);
        for (PurchaseRequestDetailDO detailDO : detailDOList) {
//            MaterialVO mv = replaceMaterialsMap.get(detailDO.getMaterialsNo());
//            if (null != mv) {
//                if (null != mv && StringUtils.isNotBlank(mv.getThjwlbh())) {
//                    detailDO.setReplaceMaterialsNo(mv.getThjwlbh());
//                }
//            }
            BigDecimal sourcePrice = detailDO.getSettlementPrice();
            if (isDirect != null && isDirect == 1) {
                PriMaterialsDO materialsDO = priMaterialsMapper.itemByNo(detailDO.getMaterialsNo(), purchaseRequestDO.getSupplierOrgId());
                if (materialsDO != null) {
                    detailDO.setPrice(materialsDO.getStandardPrice() == null ? BigDecimal.ZERO : materialsDO.getStandardPrice());
                    detailDO.setSettlementPrice(detailDO.getPrice());
                    detailDO.setApplyTotalPrice(detailDO.getQty().multiply(detailDO.getPrice()));
                    totalPrice = totalPrice.add(detailDO.getApplyTotalPrice());
                }
            }
            detailDO.setSettlementPrice(detailDO.getSettlementPrice().divide(new BigDecimal("100")));
            detailDO.setPrice(detailDO.getPrice().divide(new BigDecimal("100")));
            detailDO.setApplyTotalPrice(detailDO.getApplyTotalPrice().divide(new BigDecimal("100")));
            PurchaseRequestDetailVO purchaseRequestDetailVO = getDetailVO(detailDO);
            purchaseRequestDetailVO.setSourcePrice(sourcePrice);
            //开票信息
//            DlsddfpmxbDto ddo = dlsddfpmxbDtoMap.get(detailDO.getMaterialsNo());
//            if (null != ddo) {
//                purchaseRequestDetailVO.setDlsddfpmxbDto(ddo);
//            }
            //查询购买量
            MaterialsVO materialsVO = priMaterialsMapper.selectMinimumBuy(purchaseRequestDO.getSupplierOrgId(), detailDO.getMaterialsNo());
            if (materialsVO != null) {
                purchaseRequestDetailVO.setIsMinimumBuy(materialsVO.getIsMinimumBuy());
                purchaseRequestDetailVO.setMinimumBuy(materialsVO.getMinimumBuy());
            }

            EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum2(detailDO.getMaterialsNo(), inventoryOrgId, null, ynInventoryMap);
            if (enableAndOccupyVO != null) {
                purchaseRequestDetailVO.setIntentionNum(enableAndOccupyVO.getIntentionNum());
                purchaseRequestDetailVO.setDeliveryNum(enableAndOccupyVO.getDeliveryNum());

                BigDecimal allAmount = enableAndOccupyVO.getEnableNum() == null ? BigDecimal.ZERO : enableAndOccupyVO.getEnableNum();
                BigDecimal occupyAmount = enableAndOccupyVO.getDeliveryNum() == null ? BigDecimal.ZERO : enableAndOccupyVO.getDeliveryNum();
                BigDecimal intentionAmount = enableAndOccupyVO.getIntentionNum() == null ? BigDecimal.ZERO : enableAndOccupyVO.getIntentionNum();
                purchaseRequestDetailVO.setEnableNum(allAmount.subtract(occupyAmount));
                DataDictionaryDO dataDictionaryDO = dataDictionaryMapper.itemByCode("KYKC", purchaseRequestDO.getSupplierOrgId());
                if (dataDictionaryDO != null) {
                    purchaseRequestDetailVO.setEnableNum(purchaseRequestDetailVO.getEnableNum().subtract(intentionAmount));
                }
            }

            if (purchaseRequestDO.getPurchaseOrgId() == null) {
                throw new Exception("单据信息不完整（purchaseOrgId不能为空）");
            }
            List<MarketingActivityPriceVO> MarketingActivityDOList = marketingActivityService.activityPriceList(purchaseRequestDO.getPurchaseOrgId(), purchaseRequestDO.getSupplierOrgId(), detailDO.getMaterialsNo());
            purchaseRequestDetailVO.setMarketingActivityPriceVOList(MarketingActivityDOList);

            //判断是否是代理商
            if (null != isSap && 0 == isSap && companyType != null && "2".equals(companyType)) {
                //获取交货日期
                Date deliveryDate = saleIntentionDetailMapper.getDeliveryDate(detailDO.getMaterialsNo(), detailDO.getBillId());
                purchaseRequestDetailVO.setDeliveryDate(deliveryDate);
            }

            if (stockMap.size() > 0) {
                purchaseRequestDetailVO.setStockQuantity(stockMap.get(purchaseRequestDetailVO.getMaterialsNo()));
            }

            detailVOList.add(purchaseRequestDetailVO);
        }
        if (isDirect != null && isDirect == 1) {
            totalPrice = totalPrice.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            purchaseRequestVO.setTotalValue(totalPrice);
            purchaseRequestVO.setSettlementValue(totalPrice);
        }
        purchaseRequestVO.setMaterialsList(detailVOList);
        purchaseRequestVO.setLogDOList(purchaseRequestLogMapper.listBybillId(purchaseRequestDO.getBillId()));
        if (orgId.equals(purchaseRequestVO.getSoldOrgId())) {
            if ("1".equals(companyItem.getCompanyType())) {
                purchaseRequestVO.setShowFlag(1);
            } else {
                purchaseRequestVO.setShowFlag(0);
            }
        } else {
            purchaseRequestVO.setShowFlag(0);
        }
        purchaseRequestVO.setYnSupplierFlag(companyUtil.isYN(purchaseRequestVO.getSoldOrgId()));
        if (companyUtil.isYN(orgId) && purchaseRequestVO.getDeptCode() == null) {
            CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), purchaseRequestVO.getSoldOrgId());
            if (companySupplierDO != null) {
                purchaseRequestVO.setDeptCode(companySupplierDO.getDeptCode());
                purchaseRequestVO.setDeptName(companySupplierDO.getDeptName());
                purchaseRequestVO.setPurchaseCode(companySupplierDO.getPurchaseCode());
                purchaseRequestVO.setPurchaseName(companySupplierDO.getPurchaseName());
            }
        }
        if (!companyUtil.isYN(orgId)) {
            CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), orgId);
            if (companySupplierDO != null) {
                purchaseRequestVO.setSupplierFlag(1);
            } else {
                purchaseRequestVO.setSupplierFlag(0);
            }
        }
        return purchaseRequestVO;
    }

//    private Map<String, DlsddfpmxbDto> queryFpdDetailsMapByBillNo(String billNo) {
//        if (StringUtils.isBlank(billNo)) {
//            return null;
//        }
//        try {
//            DlsddfpmxbDto dto = new DlsddfpmxbDto();
//            dto.setDlsddcode(billNo);
//            ActionResult<Map<String, DlsddfpmxbDto>> rsp = erpSyncClient.queryFpdDetails(dto);
//            if (null != rsp && null != rsp.getValue()) {
//                return rsp.getValue();
//            }
//        } catch (Exception e) {
//            log.info("", e);
//        }
//        return Maps.newHashMap();
//    }
//
//    public Map<String, MaterialVO> queryReplaceMaterialsMap(List<PurchaseRequestDetailDO> detailDOList) {
//        if (CollectionUtils.isEmpty(detailDOList)) {
//            return Maps.newHashMap();
//        }
//        try {
//            List<String> list = new ArrayList<>(detailDOList.size());
//            detailDOList.forEach(x -> list.add(x.getMaterialsNo()));
//            return queryReplaceMaterialsMap2(list);
//        } catch (Exception e) {
//            logger.error("queryReplaceMaterialsMap error", e);
//        }
//        return Maps.newHashMap();
//    }
//
//    public Map<String, MaterialVO> queryReplaceMaterialsMap2(List<String> list) {
////        if (CollectionUtils.isEmpty(list)) {
////            return Maps.newHashMap();
////        }
////        try {
////            ActionResult<List<MaterialVO>> rsp = erpSyncClient.queryVoListByCodes(list);
////            if (null != rsp && CollectionUtils.isNotEmpty(rsp.getValue())) {
////                return doGetReplaceMaterialsMap(rsp.getValue());
////            }
////        } catch (Exception e) {
////            logger.error("queryReplaceMaterialsMap2 error", e);
////        }
//        return Maps.newHashMap();
//    }
//
//    private Map<String, MaterialVO> doGetReplaceMaterialsMap(List<MaterialVO> list) {
//        list.sort(Comparator.comparing(MaterialVO::getErpImportTime));
//        return list.stream().collect(Collectors.toMap(x -> x.getMaterialCode(), x -> x, (k1, k2) -> k2));
//    }

    public PurchaseRequestVO itemByIds(List<String> ids, String orgId) {
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(ids.get(0));
        if (purchaseRequestDO == null) {
            return null;
        }
        PurchaseRequestVO purchaseRequestVO = getVO(purchaseRequestDO, orgId);
        List<PurchaseRequestDetailVO> list = new ArrayList<>();
        for (String id : ids) {
            PurchaseRequestDO requestDO = purchaseRequestMapper.item(id);
            List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(id);
            List<PurchaseRequestDetailVO> detailVOList = new ArrayList<>();
            for (PurchaseRequestDetailDO detailDO : detailDOList) {
                detailDO.setSettlementPrice(detailDO.getSettlementPrice().divide(new BigDecimal("100")));
                detailDO.setPrice(detailDO.getPrice().divide(new BigDecimal("100")));
                detailDO.setApplyTotalPrice(detailDO.getApplyTotalPrice().divide(new BigDecimal("100")));
                PurchaseRequestDetailVO purchaseRequestDetailVO = getDetailVO(detailDO);
                purchaseRequestDetailVO.setSourceId(requestDO.getBillId());
                purchaseRequestDetailVO.setSourceOrder(requestDO.getBillNo());
                purchaseRequestDetailVO.setInitialOrder(requestDO.getDirectSourceOrder());
                purchaseRequestDetailVO.setRowNo(detailDO.getRowNo());
                detailVOList.add(purchaseRequestDetailVO);
            }
            list.addAll(detailVOList);
        }
        purchaseRequestVO.setMaterialsList(list);
        return purchaseRequestVO;
    }

    public void download() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateExcelFileName);
    }

    public void downloadReplaceTemp() throws Exception {
        FileUtil.downLoadFile(response, filePath, replaceTemplateExcelFileName);
    }


    public FunctionResult importReplaceExcel(String billId, InputStream in, String dealerOrgId, String orgId, String isDirectCast, String soldOrgId, String supplierCode) throws Exception {
        FunctionResult result = new FunctionResult();
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(billId);
        if (purchaseRequestDO == null) {
            result.setCode(ErrorCode.Failure);
            result.setValue("订单不存在");
            return result;
        }
        SaleIntentionDO saleIntentionDO = saleIntentionMapper.itemByPurchaseNo(purchaseRequestDO.getBillNo(), purchaseRequestDO.getSupplierOrgId());
        if (saleIntentionDO != null) {
            result.setCode(ErrorCode.Failure);
            result.setValue("该采购单已创建销售订单，不能编辑");
            return result;
        }
        PurchaseRequestVO record = new PurchaseRequestVO();
        record.setDirectSourceOrder(purchaseRequestDO.getBillNo());
        record.setPurchaseOrgId(purchaseRequestDO.getSupplierOrgId());
        if (!ListUtil.isNullOrEmpty(purchaseRequestMapper.list(record))) {
            result.setCode(ErrorCode.Failure);
            result.setValue("该采购单已创建直投单，不能编辑");
            return result;
        }
        List<PurchaseRequestDetailVO> detailVOList = new ArrayList<>();
        List<PurchaseRequestDetailVO> errorDetailVOList = new ArrayList<>();
        HSSFWorkbook wb = new HSSFWorkbook(in);
        HSSFSheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(2).getLastCellNum();
        if (totalCell != 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }

        //获取采购订单详情
        PurchaseRequestVO purchaseRequestVO = this.item(billId, null, orgId);

        for (PurchaseRequestDetailVO requestDetailVO : purchaseRequestVO.getMaterialsList()) {
            List<MarketingActivityPriceVO> marketingActivityPriceVOS = marketingActivityService.activityPriceList(dealerOrgId, orgId, requestDetailVO.getMaterialsNo());
            requestDetailVO.setMarketingActivityPriceVOList(marketingActivityPriceVOS);
            detailVOList.add(requestDetailVO);
        }

        //采购订单零件集合
        List<String> materialsNos = detailVOList.stream().map(PurchaseRequestDetailVO::getMaterialsNo).distinct().collect(Collectors.toList());

        for (int i = 3; i <= totalRow; i++) {
            HSSFRow curRow = sheet.getRow(i);
            PurchaseRequestDetailVO detailVO = new PurchaseRequestDetailVO();
            if (curRow == null) {
                detailVO.setErrorRow(i);
                detailVO.setRemark("无数据");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (isRowEmpty(curRow)) {
                continue;
            }
            String oldMaterialsNo = excelValue(curRow, 1);
            String newMaterialsNo = excelValue(curRow, 2);

            MaterialsVO oldMaterialsVO = materialsService.itemByNo(oldMaterialsNo, orgId);
            if (oldMaterialsVO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark(oldMaterialsNo + "原零件信息不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }

            MaterialsVO newMaterialsVO = materialsService.itemByNo(newMaterialsNo, orgId);
            if (newMaterialsVO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark(newMaterialsNo + "新零件信息不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }

            //替换零件在原零件中存在，不允许替换
            if (materialsNos.contains(newMaterialsNo)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("新零件号【" + newMaterialsNo + "】在采购单中已存在，不允许替换");
                errorDetailVOList.add(detailVO);
                continue;
            }

            if (isDirectCast != null && "1".equals(isDirectCast) && newMaterialsVO.getIsDirectCast().equals(0)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件非直投零件");
                errorDetailVOList.add(detailVO);
                continue;
            }

            if (isDirectCast != null && "1".equals(isDirectCast) && !StringUtil.isNullOrEmpty(soldOrgId)) {
                MaterialsSupplierDO materialsSupplierDO = materialsSupplierMapper.findBySupplierOrgIdAndSalesCode(soldOrgId, orgId, newMaterialsNo, "1006");
                if (materialsSupplierDO == null) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("零件非此供应商下零件");
                    errorDetailVOList.add(detailVO);
                    continue;
                }
            }
            //materialsPurchaseInfoService.getMaterialsPurchaseInfoFromSap()
            boolean flag = false;
            for (PurchaseRequestDetailVO requestDetailVO : detailVOList) {
                if (StringUtils.equals(requestDetailVO.getMaterialsNo(), oldMaterialsNo)) {
                    flag = true;
                    requestDetailVO.setIsReplaceMaterial("1");
                    requestDetailVO.setOriginalMaterialsNo(requestDetailVO.getMaterialsNo());
                    requestDetailVO.setMaterialsId(newMaterialsVO.getMaterialsId());
                    requestDetailVO.setMaterialsNo(newMaterialsVO.getMaterialsNo());
                    requestDetailVO.setMaterialsDes(newMaterialsVO.getMaterialsDes());
                    BigDecimal newPrice = newMaterialsVO.getPrice();
                    if (newPrice == null) {
                        newPrice = BigDecimal.ZERO;
                    }
                    requestDetailVO.setPrice(newPrice);
                    requestDetailVO.setSettlementPrice(newPrice);
                    requestDetailVO.setUnit(newMaterialsVO.getUnit());
                    requestDetailVO.setIsMinimumBuy(newMaterialsVO.getIsMinimumBuy());
                    requestDetailVO.setMinimumBuy(newMaterialsVO.getMinimumBuy());
                    if (newMaterialsVO.getPrice() == null) {
                        newMaterialsVO.setPrice(new BigDecimal(1));
                        requestDetailVO.setPrice(new BigDecimal(1));
                        requestDetailVO.setSettlementPrice(new BigDecimal(1));
                    }
                    MarketingActivityPriceVO marInfo = marketingActivityService.activityPriceModel(dealerOrgId, orgId, detailVO.getMaterialsNo());
                    requestDetailVO.setSettlementPrice(newMaterialsVO.getPrice());
                    if (marInfo != null) {
                        requestDetailVO.setSettlementPrice(marInfo.getDiscountPrice());
                        requestDetailVO.setPriceSchemeId(marInfo.getActivityId());
                        requestDetailVO.setPriceSchemeName(marInfo.getName());
                    }
                    EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum(detailVO.getMaterialsNo(), orgId, null);
                    if (enableAndOccupyVO != null) {
                        requestDetailVO.setIntentionNum(enableAndOccupyVO.getIntentionNum());
                        requestDetailVO.setDeliveryNum(enableAndOccupyVO.getDeliveryNum());
                        requestDetailVO.setEnableNum(enableAndOccupyVO.getEnableNum());
                    }
                    if (StringUtils.isNotBlank(requestDetailVO.getPriceSchemeId())) {
                        BigDecimal targetPrice = calculatePrice(requestDetailVO.getPriceSchemeId(), requestDetailVO.getPrice(), dealerOrgId, orgId, requestDetailVO.getMaterialsNo(), soldOrgId);
                        requestDetailVO.setSettlementPrice(targetPrice);
                    }
                    requestDetailVO.setApplyTotalPrice(requestDetailVO.getSettlementPrice().multiply(requestDetailVO.getQty()));
                    newestReplace(newMaterialsVO);
                    List<MarketingActivityPriceVO> marketingActivityPriceVOS = marketingActivityService.activityPriceList(dealerOrgId, orgId, newMaterialsNo);
                    requestDetailVO.setMarketingActivityPriceVOList(marketingActivityPriceVOS);
                }
            }
            if (!flag) {
                result.setCode(ErrorCode.Failure);
                result.setValue(oldMaterialsNo + "原零件在单据中不存在");
                return result;
            }
        }

        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            //List<PurchaseRequestDetailVO> noRepeatList = ImportUtil.deRepeat(detailVOList, "MaterialsNo", "Qty", "ApplyTotalPrice", "Price");
            if (detailVOList.size() != detailVOList.size()) {
                result.setValue(detailVOList);
                result.setCode(ErrorCode.MaterialsIsRepeat);
            }
            result.setValue(detailVOList);
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }


    /**
     * 根据价格策略重新计算价格
     *
     * @param priceSchemaId 价格策略ID
     * @param sourcePrice   原价格
     * @return 计算后的价格
     */
    public BigDecimal calculatePrice(String priceSchemaId, BigDecimal sourcePrice, String dealerOrgId, String orgId, String materialsNo, String soldOrgId) {
        if (StringUtils.isBlank(priceSchemaId) || sourcePrice == null) {
            return sourcePrice;
        }
        MarketingActivityDO marketingActivityDO = marketingActivityService.itemValid(priceSchemaId);
        if (marketingActivityDO != null) {
            //价格策略如果是固定折扣
            if (marketingActivityDO.getModeType() != null
                    && marketingActivityDO.getModeType() == 0
                    && marketingActivityDO.getModeRate() != null) {
                BigDecimal targetPrice = BigDecimal.ZERO;
                //如果是标准价的价格方案
                if (StringUtils.equals("1", marketingActivityDO.getPriceType()) && soldOrgId != null) {
                    //取当前零件对应的标准价
                    PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNoOrgId(materialsNo, soldOrgId);
                    if (priMaterialsDO != null && priMaterialsDO.getStandardPrice() != null) {
                        targetPrice = priMaterialsDO.getStandardPrice().multiply(marketingActivityDO.getModeRate()).divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP, 2);
                    }
                } else {
                    targetPrice = sourcePrice.multiply(marketingActivityDO.getModeRate());
                }
                return targetPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
            } else if (marketingActivityDO.getModeType() != null
                    && marketingActivityDO.getModeType() == 1) {

                MarketingMaterialsVO marketingMaterialsVO = marketingMaterialsMapper.itemByActivityMaterials(orgId, materialsNo, marketingActivityDO.getId());
                if (marketingMaterialsVO != null) {
                    if (marketingMaterialsVO.getPrice() != null) {
                        return marketingMaterialsVO.getPrice().divide(new BigDecimal(100));
                    }
                }
            }
        }
        return sourcePrice;
    }


    public FunctionResult importExcel(InputStream in, String dealerOrgId, String orgId, String isDirectCast,
                                      String soldOrgId, String supplierCode) throws Exception {
        FunctionResult result = new FunctionResult();
        List<PurchaseRequestDetailVO> detailVOList = new ArrayList<>();
        List<PurchaseRequestDetailVO> errorDetailVOList = new ArrayList<>();
        HSSFWorkbook wb = new HSSFWorkbook(in);
        HSSFSheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(2).getLastCellNum();
        if (totalCell != 6) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<String> mcodes = new ArrayList<>();
        for (int i = 3; i <= totalRow; i++) {
            HSSFRow curRow = sheet.getRow(i);
            PurchaseRequestDetailVO detailVO = new PurchaseRequestDetailVO();
            if (curRow == null) {
                detailVO.setErrorRow(i);
                detailVO.setRemark("无数据");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (isRowEmpty(curRow)) {
                continue;
            }
            curRow.getCell(1).setCellType(CellType.STRING);
            String materialsNo = curRow.getCell(1).getStringCellValue();
            materialsNo = materialsNo != null ? materialsNo.trim() : materialsNo;
            String qty = excelValue(curRow, 3);
            String jhDate = excelValue(curRow, 4);
            String machineModel = excelValue(curRow, 5);
            if (!isInteger(qty) || "0".equals(qty)) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("入库数量格式不正确");
                errorDetailVOList.add(detailVO);
                continue;
            }
            MaterialsVO materialsVO = materialsService.itemByNo(materialsNo, orgId);
            if (materialsVO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件信息不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (materialsVO.getValidFlag() != null && Integer.valueOf(1).equals(materialsVO.getValidFlag())) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件信息已停用");
                errorDetailVOList.add(detailVO);
                continue;
            }
            boolean directM = (null != materialsVO.getIsDirectCast() && materialsVO.getIsDirectCast().equals(1)) ||
                    (null != materialsVO.getIsDirectCastHF() && materialsVO.getIsDirectCastHF().equals(1));
            if (isDirectCast != null && "1".equals(isDirectCast) && !directM) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件非直投零件");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if (isDirectCast != null && "1".equals(isDirectCast) && !StringUtil.isNullOrEmpty(soldOrgId)) {
                MaterialsSupplierDO materialsSupplierDO = materialsSupplierMapper.findBySupplierOrgIdAndSalesCode(soldOrgId, orgId, materialsNo, "1006");
                if (materialsSupplierDO == null) {
                    detailVO.setErrorRow(i + 1);
                    detailVO.setRemark("零件非此供应商下零件");
                    errorDetailVOList.add(detailVO);
                    continue;
                }
            }
            //materialsPurchaseInfoService.getMaterialsPurchaseInfoFromSap()
            BigDecimal intQty = new BigDecimal(qty);
            BigDecimal max = new BigDecimal(99999999.99);
            if (intQty.compareTo(max) > 0) {
                intQty = max;
            }
            detailVO.setMaterialsId(materialsVO.getMaterialsId());
            detailVO.setMaterialsNo(materialsVO.getMaterialsNo());
            detailVO.setMaterialsDes(materialsVO.getMaterialsDes());
            detailVO.setPrice(materialsVO.getPrice());
            detailVO.setSettlementPrice(materialsVO.getPrice());
            detailVO.setQty(intQty);
            detailVO.setUnit(materialsVO.getUnit());
            detailVO.setIsMinimumBuy(materialsVO.getIsMinimumBuy());
            detailVO.setMinimumBuy(materialsVO.getMinimumBuy());
            if (materialsVO.getPrice() == null) {
                materialsVO.setPrice(new BigDecimal(1));
                detailVO.setPrice(new BigDecimal(1));
                detailVO.setSettlementPrice(new BigDecimal(1));
            }
            detailVO.setApplyTotalPrice(materialsVO.getPrice().multiply(intQty));
            MarketingActivityPriceVO marInfo = marketingActivityService.activityPriceModel(dealerOrgId, orgId, detailVO.getMaterialsNo());
            detailVO.setSettlementPrice(materialsVO.getPrice());
            if (marInfo != null) {
                detailVO.setSettlementPrice(marInfo.getDiscountPrice());
                detailVO.setPriceSchemeId(marInfo.getActivityId());
                detailVO.setPriceSchemeName(marInfo.getName());
            }
            mcodes.add(detailVO.getMaterialsNo());
            EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum(detailVO.getMaterialsNo(), orgId, null);
            if (enableAndOccupyVO != null) {
                detailVO.setIntentionNum(enableAndOccupyVO.getIntentionNum());
                detailVO.setDeliveryNum(enableAndOccupyVO.getDeliveryNum());
                detailVO.setEnableNum(enableAndOccupyVO.getEnableNum());
            }
            newestReplace(materialsVO);
            List<MarketingActivityPriceVO> marketingActivityPriceVOS = marketingActivityService.activityPriceList(dealerOrgId, orgId, materialsNo);
            detailVO.setMarketingActivityPriceVOList(marketingActivityPriceVOS);
            detailVO.setReplaceMaterialsNo(materialsVO.getReplaceMaterialsNo());
            detailVO.setReplaceMaterialsDes(materialsVO.getReplaceMaterialsDes());
            detailVO.setRetrofitMaterialsNo(materialsVO.getRetrofitMaterialsNo());
            detailVO.setReplaceMaterialsDes(materialsVO.getReplaceMaterialsDes());
            detailVO.setCustomMaterialsNo(materialsVO.getCustomMaterialsNo());
            detailVO.setSelfMade(materialsVO.getSelfMade());
            detailVO.setBasicMachine(materialsVO.getBasicMachine());
            setDeliveryDate(detailVO, jhDate, materialsNo, orgId, supplierCode);
            detailVO.setMachineModel(machineModel);
            detailVOList.add(detailVO);
        }
        Map<String, BigDecimal> ynInventoryMap = marketingActivityService.queryYnInventoryMapByMaterials(mcodes, supplierCode);
        if (MapUtils.isNotEmpty(ynInventoryMap)) {
            for (PurchaseRequestDetailVO v : detailVOList) {
                v.setEnableNum(ynInventoryMap.get(v.getMaterialsNo()));
            }
        }

        if (ListUtil.isNullOrEmpty(errorDetailVOList)) {
            List<PurchaseRequestDetailVO> noRepeatList = ImportUtil.deRepeat(detailVOList, "MaterialsNo", "Qty", "ApplyTotalPrice", "Price");
            if (noRepeatList.size() != detailVOList.size()) {
                result.setValue(noRepeatList);
                result.setCode(ErrorCode.MaterialsIsRepeat);
            }
            result.setValue(noRepeatList);
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    private void setDeliveryDate(PurchaseRequestDetailVO detailVO, String jhDate, String materialsNo, String orgId, String supplierCode) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date deliveryDate = null;
        if (!ObjectUtils.isEmpty(jhDate)) {
            try {
                deliveryDate = simpleDateFormat.parse(jhDate);
            } catch (ParseException e) {
                log.error("采购订单导入，交货期转换失败", e);
                throw new RuntimeException("日期转换失败");
            }
            detailVO.setDeliveryDate(deliveryDate);
            return;
        }
        List<MaterialsPurchaseInfo> materialsPurchaseInfos = materialsPurchaseInfoService.selectByOrgIdAndMaterialNoAndSupplierCode(materialsNo, orgId, supplierCode);
        if (ObjectUtils.isEmpty(materialsPurchaseInfos)) {
            log.info("零件采购信息不存在");
            return;
        }
        BigDecimal deliverySpend = materialsPurchaseInfos.get(0).getDeliverySpend();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, deliverySpend.intValue() * 30);
        detailVO.setDeliveryDate(calendar.getTime());
    }

    /**
     * 获取最新的替换和改型零件
     */
    private void newestReplace(MaterialsVO model) {
        PriMaterialsDO replaceDo = new PriMaterialsDO();
        BeanUtils.copyProperties(model, replaceDo);
        if (model.getReplaceMaterialsNo() != null) {
            Set<String> replaceNo = new HashSet<>();
            Set<String> replaceDes = new HashSet<>();
            getPriMaterialsDO(replaceDo, replaceNo, replaceDes);
            model.setReplaceMaterialsNo(StringUtils.join(replaceNo, ","));
            model.setReplaceMaterialsDes(StringUtils.join(replaceDes, ","));
        }
        PriMaterialsDO retrofit = null;
        PriMaterialsDO retrofitDo = new PriMaterialsDO();
        BeanUtils.copyProperties(model, retrofitDo);
        int retInt = 0;
        if (model.getRetrofitMaterialsNo() != null) {
            do {
                retInt++;
                retrofit = retrofitDo;
                if (retrofitDo.getRetrofitMaterialsNo() == null || retrofitDo.getReplaceMaterialsNo().equals(retrofitDo.getMaterialsNo())) {
                    break;
                }
                if (retInt > 20) {
                    break;
                }
                retrofitDo = priMaterialsMapper.itemByNo(retrofitDo.getRetrofitMaterialsNo(), retrofitDo.getOrgId());
            } while (retrofitDo != null);
            if (retrofit != null) {
                model.setRetrofitMaterialsNo(retrofit.getMaterialsNo());
                model.setRetrofitMaterialsDes(retrofit.getMaterialsDes());
            }
        }
    }

    private void getPriMaterialsDO(PriMaterialsDO replaceDo, Set<String> replaceNo, Set<String> replaceDes) {
        if (null == replaceDo) {
            return;
        }

        String[] arrReplaceMaterialsNo = replaceDo.getReplaceMaterialsNo().split(",");
        for (String replaceMaterialsNo : arrReplaceMaterialsNo) {
            int repInt = 0;
            PriMaterialsDO replace = replaceDo;
            if (replaceMaterialsNo.equals(replaceDo.getMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            replaceDo = priMaterialsMapper.itemByNo(replaceMaterialsNo, replaceDo.getOrgId());
            if (null == replaceDo) {
                replaceNo.add(replace.getMaterialsNo());
                replaceDes.add(replace.getMaterialsDes());
                continue;
            }
            if (StringUtils.isBlank(replaceDo.getReplaceMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            getPriMaterialsNO(replaceDo, replaceNo, replaceDes, repInt);
        }
    }

    private void getPriMaterialsNO(PriMaterialsDO replaceDo, Set<String> replaceNo, Set<String> replaceDes, int repInt) {
        if (null == replaceDo) {
            return;
        }
        String[] arrReplaceMaterialsNo = replaceDo.getReplaceMaterialsNo().split(",");
        for (String replaceMaterialsNo : arrReplaceMaterialsNo) {
            if (repInt > 20) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            repInt++;
            PriMaterialsDO replace = replaceDo;
            if (replaceMaterialsNo.equals(replaceDo.getMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            replaceDo = priMaterialsMapper.itemByNo(replaceMaterialsNo, replaceDo.getOrgId());
            if (null == replaceDo) {
                replaceNo.add(replace.getMaterialsNo());
                replaceDes.add(replace.getMaterialsDes());
                continue;
            }
            if (StringUtils.isBlank(replaceDo.getReplaceMaterialsNo())) {
                replaceNo.add(replaceDo.getMaterialsNo());
                replaceDes.add(replaceDo.getMaterialsDes());
                continue;
            }
            getPriMaterialsNO(replaceDo, replaceNo, replaceDes, repInt);
        }
    }

    private String excelValue(HSSFRow curRow, Integer line) {
        Cell cell = curRow.getCell(line);
        String cellValue = "";
        if (null != cell) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                    DecimalFormat df = new DecimalFormat("0");
                    cellValue = df.format(cell.getNumericCellValue());
                    break;

                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    cellValue = cell.getStringCellValue();
                    break;

                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                    cellValue = cell.getBooleanCellValue() + "";
                    break;

                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                    cellValue = cell.getCellFormula() + "";
                    break;

                case HSSFCell.CELL_TYPE_BLANK: // 空值
                    cellValue = "";
                    break;

                case HSSFCell.CELL_TYPE_ERROR: // 故障
                    cellValue = "";
                    break;

                default:
                    cellValue = "";
                    break;
            }
        }
        return cellValue;
    }

    private boolean isInteger(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        try {
            BigDecimal decimal = new BigDecimal(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static boolean isRowEmpty(HSSFRow row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            HSSFCell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && !StringUtil.isNullOrSpace(ExcelUtil.getCellStringValue(cell))) {
                return false;
            }
        }
        return true;
    }

    private static boolean isNumber(String str) {
        if (str == null) {
            return false;
        }
        String reg = "-?[0-9]+.*[0-9]*";
        return str.matches(reg);
    }

    private PurchaseRequestVO getVO(PurchaseRequestDO purchaseRequestDO, String orgId) {
        PurchaseRequestVO purchaseRequestVO = new PurchaseRequestVO();
        BeanUtils.copyProperties(purchaseRequestDO, purchaseRequestVO);
        purchaseRequestVO.setBillId(purchaseRequestDO.getBillId());
        purchaseRequestVO.setBillNo(purchaseRequestDO.getBillNo());
        purchaseRequestVO.setPurchaseOrgId(purchaseRequestDO.getPurchaseOrgId());
        purchaseRequestVO.setPurchaseOrgName(purchaseRequestDO.getPurchaseOrgName());
        purchaseRequestVO.setSupplierOrgId(purchaseRequestDO.getSupplierOrgId());
        purchaseRequestVO.setSupplierOrgName(purchaseRequestDO.getSupplierOrgName());
        purchaseRequestVO.setDispatcherId(purchaseRequestDO.getDispatcherId());
        purchaseRequestVO.setDispatcherName(purchaseRequestDO.getDispatcherName());
        purchaseRequestVO.setPurchaseType(purchaseRequestDO.getPurchaseType());
        purchaseRequestVO.setTotalValue(purchaseRequestDO.getTotalValue());
        purchaseRequestVO.setSettlementValue(purchaseRequestDO.getSettlementValue());
        purchaseRequestVO.setShippingMethod(purchaseRequestDO.getShippingMethod());
        purchaseRequestVO.setShippingMethodId(purchaseRequestDO.getShippingMethodId());
        purchaseRequestVO.setReceiverName(purchaseRequestDO.getReceiverName());
        purchaseRequestVO.setReceiverTel(purchaseRequestDO.getReceiverTel());
        purchaseRequestVO.setReceiverFax(purchaseRequestDO.getReceiverFax());
        purchaseRequestVO.setReceiverAddress(purchaseRequestDO.getReceiverAddress());
        purchaseRequestVO.setRemark(purchaseRequestDO.getRemark());
        purchaseRequestVO.setBillStatus(purchaseRequestDO.getBillStatus());
        purchaseRequestVO.setCreateId(purchaseRequestDO.getCreateId());
        purchaseRequestVO.setCreateDate(purchaseRequestDO.getCreateDate());
        purchaseRequestVO.setCreateOrgId(purchaseRequestDO.getCreateOrgId());
        purchaseRequestVO.setUpdateId(purchaseRequestDO.getUpdateId());
        purchaseRequestVO.setUpdateDate(purchaseRequestDO.getUpdateDate());
        purchaseRequestVO.setAuditId(purchaseRequestDO.getAuditId());
        purchaseRequestVO.setAuditName(purchaseRequestDO.getAuditName());
        purchaseRequestVO.setAuditDate(purchaseRequestDO.getAuditDate());
        purchaseRequestVO.setAuditMessage(purchaseRequestDO.getAuditMessage());
        purchaseRequestVO.setDel(purchaseRequestDO.getDel());
        purchaseRequestVO.setStatusDesc(purchaseRequestDO.getStatusDesc());
        purchaseRequestVO.setTypeDesc(purchaseRequestDO.getTypeDesc());
        purchaseRequestVO.setCreateName(purchaseRequestDO.getCreateName());
        purchaseRequestVO.setUpdateName(purchaseRequestDO.getUpdateName());
        purchaseRequestVO.setStatus(purchaseRequestDO.getStatus());
        purchaseRequestVO.setIsSale(purchaseRequestDO.getIsSale());
        purchaseRequestVO.setInboundEnable(purchaseRequestDO.getInboundEnable());
        purchaseRequestVO.setIsImprove(purchaseRequestDO.getIsImprove());
        purchaseRequestVO.setPurchaseTypeChildId(purchaseRequestDO.getPurchaseTypeChildId());
        purchaseRequestVO.setPurchaseTypeChildName(purchaseRequestDO.getPurchaseTypeChildName());
        purchaseRequestVO.setSendTypeChildId(purchaseRequestDO.getSendTypeChildId());
        purchaseRequestVO.setSendTypeChildName(purchaseRequestDO.getSendTypeChildName());
        if (Integer.valueOf(1).equals(purchaseRequestDO.getIsDirectCast()) && !orgId.equals(purchaseRequestDO.getDeliveryOrgId())) {
            CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), purchaseRequestDO.getSoldOrgId());
            if (companySupplierDO != null) {
                purchaseRequestVO.setSoldOrgName(companySupplierDO.getCompanyName());
            }
        }
        Integer forward = purchaseRequestDO.getForward();
        forward = forward == null ? 0 : forward;
        purchaseRequestVO.setForward(forward);
        purchaseRequestVO.setDeptCode(purchaseRequestDO.getDeptCode());
        purchaseRequestVO.setDeptName(purchaseRequestDO.getDeptName());
        purchaseRequestVO.setPurchaseCode(purchaseRequestDO.getPurchaseCode());
        purchaseRequestVO.setPurchaseName(purchaseRequestDO.getPurchaseName());
        return purchaseRequestVO;
    }

    private PurchaseRequestDO getDO(PurchaseRequestVO purchaseRequestVO) {
        PurchaseRequestDO purchaseRequestDO = new PurchaseRequestDO();
        BeanUtils.copyProperties(purchaseRequestVO, purchaseRequestDO);
        purchaseRequestDO.setBillId(purchaseRequestVO.getBillId());
        purchaseRequestDO.setBillNo(purchaseRequestVO.getBillNo());
        purchaseRequestDO.setPurchaseOrgId(purchaseRequestVO.getPurchaseOrgId());
        purchaseRequestDO.setPurchaseOrgName(purchaseRequestVO.getPurchaseOrgName());
        purchaseRequestDO.setSupplierOrgId(purchaseRequestVO.getSupplierOrgId());
        purchaseRequestDO.setSupplierOrgName(purchaseRequestVO.getSupplierOrgName());
        purchaseRequestDO.setDispatcherId(purchaseRequestVO.getDispatcherId());
        purchaseRequestDO.setDispatcherName(purchaseRequestVO.getDispatcherName());
        purchaseRequestDO.setPurchaseType(purchaseRequestVO.getPurchaseType());
        purchaseRequestDO.setTotalValue(purchaseRequestVO.getTotalValue());
        purchaseRequestDO.setSettlementValue(purchaseRequestVO.getSettlementValue());
        purchaseRequestDO.setShippingMethod(purchaseRequestVO.getShippingMethod());
        purchaseRequestDO.setShippingMethodId(purchaseRequestVO.getShippingMethodId());
        purchaseRequestDO.setReceiverName(purchaseRequestVO.getReceiverName());
        purchaseRequestDO.setReceiverTel(purchaseRequestVO.getReceiverTel());
        purchaseRequestDO.setReceiverFax(purchaseRequestVO.getReceiverFax());
        purchaseRequestDO.setReceiverAddress(purchaseRequestVO.getReceiverAddress());
        purchaseRequestDO.setRemark(purchaseRequestVO.getRemark());
        purchaseRequestDO.setBillStatus(purchaseRequestVO.getBillStatus());
        purchaseRequestDO.setCreateId(purchaseRequestVO.getCreateId());
        purchaseRequestDO.setCreateDate(purchaseRequestVO.getCreateDate());
        purchaseRequestDO.setCreateOrgId(purchaseRequestVO.getCreateOrgId());
        purchaseRequestDO.setUpdateId(purchaseRequestVO.getUpdateId());
        purchaseRequestDO.setUpdateDate(purchaseRequestVO.getUpdateDate());
        purchaseRequestDO.setAuditId(purchaseRequestVO.getAuditId());
        purchaseRequestDO.setAuditName(purchaseRequestVO.getAuditName());
        purchaseRequestDO.setAuditDate(purchaseRequestVO.getAuditDate());
        purchaseRequestDO.setAuditMessage(purchaseRequestVO.getAuditMessage());
        purchaseRequestDO.setDel(purchaseRequestVO.getDel());
        purchaseRequestDO.setStatusDesc(purchaseRequestVO.getStatusDesc());
        purchaseRequestDO.setTypeDesc(purchaseRequestVO.getTypeDesc());
        purchaseRequestDO.setCreateName(purchaseRequestVO.getCreateName());
        purchaseRequestDO.setUpdateName(purchaseRequestVO.getUpdateName());
        purchaseRequestDO.setIsImprove(purchaseRequestVO.getIsImprove());
        purchaseRequestDO.setPurchaseTypeChildId(purchaseRequestVO.getPurchaseTypeChildId());
        purchaseRequestDO.setPurchaseTypeChildName(purchaseRequestVO.getPurchaseTypeChildName());
        purchaseRequestDO.setPurchaseOrdType(purchaseRequestVO.getPurchaseOrdType());
        purchaseRequestDO.setPurchaseOrdTypeDesc(purchaseRequestVO.getPurchaseOrdTypeDesc());
        purchaseRequestDO.setSendTypeChildId(purchaseRequestVO.getSendTypeChildId());
        purchaseRequestDO.setSendTypeChildName(purchaseRequestVO.getSendTypeChildName());
        purchaseRequestDO.setSubmitDate(purchaseRequestVO.getSubmitDate());
        purchaseRequestDO.setSendCompanyCode(purchaseRequestVO.getSendCompanyCode());
        purchaseRequestDO.setSendCompanyName(purchaseRequestVO.getSendCompanyName());
        purchaseRequestDO.setCompanyType(purchaseRequestVO.getCompanyType());
        purchaseRequestDO.setTotalQuantity(purchaseRequestVO.getTotalQuantity());
        purchaseRequestDO.setDeptCode(purchaseRequestVO.getDeptCode());
        purchaseRequestDO.setDeptName(purchaseRequestVO.getDeptName());
        purchaseRequestDO.setPurchaseCode(purchaseRequestVO.getPurchaseCode());
        purchaseRequestDO.setPurchaseName(purchaseRequestVO.getPurchaseName());
        purchaseRequestDO.setDeptCode(purchaseRequestVO.getDeptCode());
        purchaseRequestDO.setDeptName(purchaseRequestVO.getDeptName());
        purchaseRequestDO.setPurchaseCode(purchaseRequestVO.getPurchaseCode());
        purchaseRequestDO.setPurchaseName(purchaseRequestVO.getPurchaseName());
        Integer forward = purchaseRequestVO.getForward();
        forward = forward == null ? 0 : forward;
        purchaseRequestDO.setForward(forward);
        return purchaseRequestDO;
    }

    private PurchaseRequestDetailDO getDetailDO(PurchaseRequestDetailVO purchaseRequestDetailVO) {
        PurchaseRequestDetailDO purchaseRequestDetailDO = new PurchaseRequestDetailDO();
        BeanUtils.copyProperties(purchaseRequestDetailVO, purchaseRequestDetailDO);
        purchaseRequestDetailDO.setBillId(purchaseRequestDetailVO.getBillId());
        purchaseRequestDetailDO.setMaterialsNo(purchaseRequestDetailVO.getMaterialsNo());
        purchaseRequestDetailDO.setCustomMaterialsNo(purchaseRequestDetailVO.getCustomMaterialsNo());
        purchaseRequestDetailDO.setMaterialsDes(purchaseRequestDetailVO.getMaterialsDes());
        purchaseRequestDetailDO.setUnit(purchaseRequestDetailVO.getUnit());
        purchaseRequestDetailDO.setPrice(purchaseRequestDetailVO.getPrice());
        purchaseRequestDetailDO.setSettlementPrice(purchaseRequestDetailVO.getSettlementPrice());
        purchaseRequestDetailDO.setQty(purchaseRequestDetailVO.getQty());
        purchaseRequestDetailDO.setApplyTotalPrice(purchaseRequestDetailVO.getApplyTotalPrice());
        purchaseRequestDetailDO.setMaterialsId(purchaseRequestDetailVO.getMaterialsId());
        purchaseRequestDetailDO.setPriceSchemeId(purchaseRequestDetailVO.getPriceSchemeId());
        purchaseRequestDetailDO.setPriceSchemeName(purchaseRequestDetailVO.getPriceSchemeName());

        return purchaseRequestDetailDO;
    }

    private PurchaseRequestDetailVO getDetailVO(PurchaseRequestDetailDO purchaseRequestDetailDO) {
        PurchaseRequestDetailVO purchaseRequestDetailVO = new PurchaseRequestDetailVO();
        BeanUtils.copyProperties(purchaseRequestDetailDO, purchaseRequestDetailVO);
        purchaseRequestDetailVO.setBillId(purchaseRequestDetailDO.getBillId());
        purchaseRequestDetailVO.setMaterialsNo(purchaseRequestDetailDO.getMaterialsNo());
        purchaseRequestDetailVO.setCustomMaterialsNo(purchaseRequestDetailDO.getCustomMaterialsNo());
        purchaseRequestDetailVO.setMaterialsDes(purchaseRequestDetailDO.getMaterialsDes());
        purchaseRequestDetailVO.setUnit(purchaseRequestDetailDO.getUnit());
        purchaseRequestDetailVO.setPrice(purchaseRequestDetailDO.getPrice());
        purchaseRequestDetailVO.setSettlementPrice(purchaseRequestDetailDO.getSettlementPrice());
        purchaseRequestDetailVO.setQty(purchaseRequestDetailDO.getQty());
        purchaseRequestDetailVO.setApplyTotalPrice(purchaseRequestDetailDO.getApplyTotalPrice());
        purchaseRequestDetailVO.setMaterialsId(purchaseRequestDetailDO.getMaterialsId());
        purchaseRequestDetailVO.setSendQty(purchaseRequestDetailDO.getSendQty());
        purchaseRequestDetailVO.setPriceSchemeId(purchaseRequestDetailDO.getPriceSchemeId());
        purchaseRequestDetailVO.setPriceSchemeName(purchaseRequestDetailDO.getPriceSchemeName());
        purchaseRequestDetailVO.setCrucialDevice(purchaseRequestDetailDO.getCrucialDevice());
        purchaseRequestDetailVO.setIsRaise(purchaseRequestDetailDO.getIsRaise());
        return purchaseRequestDetailVO;
    }

    private String getCompanyName(String orgId) {
        CompanyInfoVO companyInfoVO = companyInfoService.info(orgId);
        if (companyInfoVO == null) {
            return "";
        }
        return companyInfoVO.getCompanyName();
    }

    public void exportAll(PurchaseRequestVO purchaseRequestVO) throws Exception {
        purchaseRequestVO.setBillNosList(xcmg.device.infra.StringUtil.splitList(purchaseRequestVO.getBillNos()));
        PageHelperPlus.orderBy("create_date desc");
        String supplierOrgId = purchaseRequestVO.getSupplierOrgId();
        List<String> purchaseNamesList;
        if (StringUtils.isNotEmpty(supplierOrgId)) {//说明是售卖方查询
            purchaseNamesList = companyDealerService.listFullNamesByShortName(supplierOrgId, purchaseRequestVO.getPurchaseNames());
        } else {
            purchaseNamesList = companyDealerService.listFullNamesByShortName(null, purchaseRequestVO.getPurchaseNames());
        }
        if (CollectionUtils.isNotEmpty(purchaseNamesList)) {
            purchaseRequestVO.setPurchaseNamesList(purchaseNamesList);
        }

        List<exportPurchaseVO> exportPurchaseVOS = purchaseRequestMapper.listforExport(purchaseRequestVO);
        List<PurchaseRequestDetailDO> detailDOList = new ArrayList<PurchaseRequestDetailDO>();
        for (exportPurchaseVO vo : exportPurchaseVOS) {
            PurchaseRequestDetailDO detailDO = new PurchaseRequestDetailDO();
            detailDO.setMaterialsNo(vo.getMaterialsNo());
            detailDOList.add(detailDO);
        }
//        Map<String, MaterialVO> replaceMaterialsMap = queryReplaceMaterialsMap(detailDOList);

        Map<String, List<BillStockDO>> billStockMap = new HashMap<String, List<BillStockDO>>();
        for (exportPurchaseVO vo : exportPurchaseVOS) {
//            MaterialVO materialVO = replaceMaterialsMap.get(vo.getMaterialsNo());
//            vo.setReplaceMaterialsNo(materialVO == null ? null : materialVO.getThjwlbh());
            String key = vo.getMaterialsNo() + vo.getSoldOrgId();
            List<BillStockDO> billStockDOs = billStockMap.get(key);
            if (billStockDOs == null) {
                billStockDOs = getStockInfo(purchaseRequestVO.getIsDirectCast(), vo.getSoldOrgId(), vo.getBillNo());
                if (CollectionUtils.isEmpty(billStockDOs)) {
                    billStockDOs = new ArrayList<BillStockDO>();
                }
                billStockMap.put(key, billStockDOs);
            }
            String materialsNo = vo.getMaterialsNo();
            for (BillStockDO billStockDO : billStockDOs) {
                if (materialsNo.equals(billStockDO.getMaterialCode())) {
                    vo.setStockQuantity(billStockDO.getQuantity());
                }
            }
            //获取发货数量
            Integer deliverCount = purchaseRequestMapper.getDeliveryCount(vo);
            if (deliverCount == null) {
                vo.setDeliverCount(0);
            } else {
                vo.setDeliverCount(deliverCount);
            }
        }
        executeExport(exportPurchaseVOS);
    }

    public void export(List<String> billIds) throws Exception {
        PurchaseRequestVO purchaseRequestVO = new PurchaseRequestVO();
        purchaseRequestVO.setBillIds(billIds);
        List<exportPurchaseVO> voList = purchaseRequestMapper.listforExport(purchaseRequestVO);
        List<PurchaseRequestDetailDO> detailDOList = new ArrayList<PurchaseRequestDetailDO>();
        for (exportPurchaseVO vo : voList) {
            PurchaseRequestDetailDO detailDO = new PurchaseRequestDetailDO();
            detailDO.setMaterialsNo(vo.getMaterialsNo());
            detailDOList.add(detailDO);
        }
//        Map<String, MaterialVO> replaceMaterialsMap = queryReplaceMaterialsMap(detailDOList);

        Map<String, List<BillStockDO>> billStockMap = new HashMap<String, List<BillStockDO>>();
        for (exportPurchaseVO vo : voList) {
//            MaterialVO materialVO = replaceMaterialsMap.get(vo.getMaterialsNo());
//            vo.setReplaceMaterialsNo(materialVO == null ? null : materialVO.getThjwlbh());
            String key = vo.getMaterialsNo() + vo.getSoldOrgId();
            List<BillStockDO> billStockDOs = billStockMap.get(key);
            if (billStockDOs == null) {
                billStockDOs = getStockInfo(purchaseRequestVO.getIsDirectCast(), vo.getSoldOrgId(), vo.getBillNo());
                if (CollectionUtils.isEmpty(billStockDOs)) {
                    billStockDOs = new ArrayList<BillStockDO>();
                }
                billStockMap.put(key, billStockDOs);
            }
            String materialsNo = vo.getMaterialsNo();
            for (BillStockDO billStockDO : billStockDOs) {
                if (materialsNo.equals(billStockDO.getMaterialCode())) {
                    vo.setStockQuantity(billStockDO.getQuantity());
                }
            }
            //获取发货数量
            Integer deliverCount = purchaseRequestMapper.getDeliveryCount(vo);
            if (deliverCount == null) {
                vo.setDeliverCount(0);
            } else {
                vo.setDeliverCount(deliverCount);
            }

        }
        executeExport(voList);
    }

    private void executeExport(List<exportPurchaseVO> voList) throws Exception {
        int size = CollectionUtils.isEmpty(voList) ? 1 : voList.size();
        // key :billNo ,  value:零件号---》发票信息
//        Map<String, Map<String, DlsddfpmxbDto>> fpCach = new HashMap<>(size);
//        processFp(voList, fpCach);
        String title = "采购申请数据导出";
        String[] rowsName = new String[]{"序号", "采购单号", "接收单位", "销售组织", "发出公司", "采购凭证", "采购方式", "采购金额", "发运方式", "调度员", "申请时间",
                "审核状态", "审核人", "审核时间", "审核意见", "备注", "是否直投订单", "零件编号", "自定义零件编号", "零件名称", "零件类型", "单位", "参考单价",
                "价格方案名称", "成交价", "数量", "小计", "发货数量", "入库数量", "到货时间", "客户名称", "收货人", "联系方式", "收货地址", "送达方", "来源单号", "直投供应商",
                "采购计划申请人", "采购合同号", "开票数", "发票号", "规格型号", "原零件号", "替换零件号", "替换零件名称", "备注", "备货数"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs;
        int number = 0;//序号
        for (int i = 0; i < voList.size(); i++) {
            exportPurchaseVO e = voList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = number + 1;
            objs[1] = e.getBillNo();
            objs[2] = e.getSupplierOrgName();
            objs[3] = e.getSalesCodeDes();
            objs[4] = e.getSendCompanyName();
            objs[5] = e.getVoucherNo();
            objs[6] = e.getTypeDesc();
            objs[7] = e.getSettlementValue().divide(new BigDecimal("100"));
            objs[8] = e.getShippingMethod();
            objs[9] = e.getDispatcherName();
            objs[10] = e.getCreateDate() == null ? "" : DateUtil.formatDateTime(e.getCreateDate());
            objs[11] = e.getStatusDesc();
            objs[12] = e.getAuditName();
            objs[13] = e.getAuditDate() == null ? "" : DateUtil.formatDateTime(e.getAuditDate());
            objs[14] = e.getAuditMessage();
            objs[15] = e.getRemark();
            objs[16] = e.getIsDirectCast() == 0 ? "否" : "是";
            objs[17] = e.getMaterialsNo();
            objs[18] = e.getCustomMaterialsNo();
            objs[19] = e.getMaterialsDes();
            objs[20] = e.getMaterialsType();
            objs[21] = e.getUnit();
            objs[22] = e.getPrice() == null ? "" : e.getPrice().divide(new BigDecimal("100"));
            objs[23] = e.getPriceSchemeName();
            objs[24] = e.getSettlementPrice() == null ? "" : e.getSettlementPrice().divide(new BigDecimal("100"));
            objs[25] = e.getQty();
            objs[26] = e.getApplyTotalPrice() == null ? "" : e.getApplyTotalPrice().divide(new BigDecimal("100"));
            objs[27] = e.getDeliverCount();
            objs[28] = e.getRealQty();
            objs[29] = getSendDate(e.getCreateDate());
            objs[30] = e.getPurchaseOrgName();
            objs[31] = e.getReceiverName();
            objs[32] = e.getReceiverTel();
            objs[33] = e.getReceiverAddress();
            objs[34] = e.getDeliveryOrgName();
            if (!StringUtil.isNullOrEmpty(e.getDirectSourceOrder())) {
                objs[35] = e.getDirectSourceOrder();
            } else {
                objs[35] = e.getBuyPlanOrder();
            }
            //objs[35] = e.getRemark();
            objs[36] = e.getSoldOrgName();
            if (!StringUtil.isNullOrEmpty(e.getBuyPlanOrder())) {
                objs[37] = e.getPlanCreateName();
            } else {
                objs[37] = e.getReceiverName();
            }
            objs[38] = e.getPurchaseContractNo();

//            DlsddfpmxbDto fp = e.getDlsddfpmxbDto();
//            if (null != fp) {
//                objs[39] = fp.getQuantity();
//                if (CollectionUtils.isEmpty(fp.getVoList())) {
//                    objs[40] = "";
//                } else {
//                    List<String> fphs = new ArrayList<>(fp.getVoList().size());
//                    fp.getVoList().forEach(x -> {
//                        if (StringUtils.isNotBlank(x.getTaxcontrolcode()) && !fphs.contains(x.getTaxcontrolcode())) {
//                            fphs.add(x.getTaxcontrolcode());
//                        }
//                    });
//                    objs[40] = StringUtils.join(fphs, ",");
//                }
//            } else {
            objs[39] = "";
            objs[40] = "";
//            }
            objs[41] = e.getMaterialsMeasure();

            objs[42] = e.getOriginalMaterialsNo();
            objs[43] = e.getReplaceMaterialsNo();
            objs[44] = e.getReplaceMaterialsDes();
            objs[45] = e.getDetailRemark();
            objs[46] = e.getStockQuantity();
            dataList.add(objs);
            number++;
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);

    }

//    private void processFp(List<exportPurchaseVO> voList, Map<String, Map<String, DlsddfpmxbDto>> fpCach) {
//        if (CollectionUtils.isEmpty(voList)) {
//            return;
//        }
//        voList.forEach(x -> {
//            Map<String, DlsddfpmxbDto> m = fpCach.get(x.getBillNo());
//            if (null == m) {
//                m = queryFpdDetailsMapByBillNo(x.getBillNo());
//                fpCach.put(x.getBillNo(), m);
//            }
//            if (MapUtils.isNotEmpty(m)) {
//                x.setDlsddfpmxbDto(m.get(x.getMaterialsNo()));
//            }
//        });
//    }

    /**
     * 到货时间：创建日期加30天
     *
     * @param date
     * @return
     */
    private String getSendDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH, +30);
        return sdf.format(cal.getTime());
    }

    private String getStatus(Integer status) {
        if (status == null) {
            return "";
        }
        String sta = "";
        switch (status) {
            case 0:
                sta = "未入库";
                break;
            case 1:
                sta = "部分入库";
                break;
            case 2:
                sta = "已入库";
                break;
            case 3:
                sta = "强制结单";
                break;
            default:
                return "";
        }

        return sta;
    }

    /**
     * @Author: WangKe
     * @Description: 更新采购申请详情记录入库意向数量
     * @Date: 2018/3/19 0019
     */
    public boolean updateSendQty(String purchaseNo, String materialNo, BigDecimal qty, Integer rowNo, String orgId) {
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByPurchase(purchaseNo, orgId);
        if (purchaseRequestDO == null) {
            return false;
        }
        PurchaseRequestDetailDO detailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(purchaseRequestDO.getBillId(), materialNo, rowNo);
        if (detailDO == null) {
            return false;
        }
        detailDO.setSendQty(qty);
        return purchaseRequestDetailMapper.update(detailDO) > 0;
    }

    /**
     * 根据采购单更新详情入库意向数量
     *
     * @return
     */
    public boolean updateSourceSendQty(PurchaseRequestDO purchaseRequestDO, String materialNo, BigDecimal qty, Integer rowNo) {
        PurchaseRequestDetailDO detailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(purchaseRequestDO.getBillId(), materialNo, rowNo);
        if (detailDO == null) {
            return false;
        }
        detailDO.setSendQty(qty);
        return purchaseRequestDetailMapper.update(detailDO) > 0;
    }

    /**
     * @Author: WangKe
     * @Description: 扫码入库时更新采购申请单主表和详情表相关记录状态
     * @Date: 2018/3/20 0020
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByInBound(String purchaseNo, String materailNo, BigDecimal inAmount, Integer rowNo, String orgId) throws Exception {
        Date now = new Date();
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByPurchase(purchaseNo, orgId);
        if (purchaseRequestDO == null) {
            return false;
        }
        PurchaseRequestDetailDO detailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(purchaseRequestDO.getBillId(), materailNo, rowNo);
        if (detailDO == null) {
            return false;
        }
        detailDO.setRealQty(detailDO.getRealQty().add(inAmount));
        if (detailDO.getRealQty().compareTo(detailDO.getQty()) >= 0) {
            detailDO.setStatus(2);
            detailDO.setAllInboundTime(now);
        } else {
            detailDO.setStatus(1);
        }
        boolean success = purchaseRequestDetailMapper.update(detailDO) > 0;
        if (!success) {
            return false;
        }

        //更新采购申请主表出库状态
        Integer status = 1;
        if (detailDO.getStatus() == 2) {
            List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(purchaseRequestDO.getBillId());
            if (ListUtil.isNullOrEmpty(detailDOList)) {
                return false;
            }
            status = 2;
            for (PurchaseRequestDetailDO intentionDetailDO : detailDOList) {
                if (!intentionDetailDO.getMaterialsNo().equals(materailNo) && intentionDetailDO.getStatus() != 2) {
                    status = 1;
                    break;
                }
            }
        }
        if (status.compareTo(2) == 0) {
            purchaseRequestDO.setAllInboundTime(now);
        }
        purchaseRequestDO.setStatus(status);
        return purchaseRequestMapper.update(purchaseRequestDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean updateBySendBillInBound(String purchaseNo, String materailNo, BigDecimal inAmount, Integer rowNo, String orgId) throws Exception {
        Date now = new Date();
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByPurchase(purchaseNo, orgId);
        if (purchaseRequestDO == null) {
            return false;
        }
        PurchaseRequestDetailDO detailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(purchaseRequestDO.getBillId(), materailNo, rowNo);
        if (detailDO == null) {
            return false;
        }
        detailDO.setRealQty(inAmount);
        if (detailDO.getRealQty().compareTo(detailDO.getQty()) >= 0) {
            detailDO.setStatus(2);
            detailDO.setAllInboundTime(now);
        } else {
            detailDO.setStatus(1);
        }
        boolean success = purchaseRequestDetailMapper.update(detailDO) > 0;
        if (!success) {
            return false;
        }

        //更新采购申请主表出库状态
        Integer status = 1;
        if (detailDO.getStatus() == 2) {
            List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(purchaseRequestDO.getBillId());
            if (ListUtil.isNullOrEmpty(detailDOList)) {
                return false;
            }
            status = 2;
            for (PurchaseRequestDetailDO intentionDetailDO : detailDOList) {
                if (!intentionDetailDO.getMaterialsNo().equals(materailNo) && intentionDetailDO.getStatus() != 2) {
                    status = 1;
                    break;
                }
            }
        }
        if (status.compareTo(2) == 0) {
            purchaseRequestDO.setAllInboundTime(now);
        }
        purchaseRequestDO.setStatus(status);
        return purchaseRequestMapper.update(purchaseRequestDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean directUpdateByInBound(PurchaseRequestDO purchaseRequestDO, String materailNo, BigDecimal inAmount, Integer rowNo, String orgId) throws Exception {
        Date now = new Date();
        if (purchaseRequestDO == null) {
            return false;
        }
        PurchaseRequestDetailDO detailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(purchaseRequestDO.getBillId(), materailNo, rowNo);
        if (detailDO == null) {
            return false;
        }
        detailDO.setRealQty(detailDO.getRealQty().add(inAmount));
        if (detailDO.getRealQty().compareTo(detailDO.getQty()) >= 0) {
            detailDO.setStatus(2);
            detailDO.setAllInboundTime(now);
        } else {
            detailDO.setStatus(1);
        }
        boolean success = purchaseRequestDetailMapper.update(detailDO) > 0;
        if (!success) {
            return false;
        }

        //更新采购申请主表出库状态
        Integer status = 1;
        if (detailDO.getStatus() == 2) {
            List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(purchaseRequestDO.getBillId());
            if (ListUtil.isNullOrEmpty(detailDOList)) {
                return false;
            }
            status = 2;
            for (PurchaseRequestDetailDO intentionDetailDO : detailDOList) {
                if (!intentionDetailDO.getMaterialsNo().equals(materailNo) && intentionDetailDO.getStatus() != 2) {
                    status = 1;
                    break;
                }
            }
        }
        if (status.compareTo(2) == 0) {
            purchaseRequestDO.setAllInboundTime(now);
        }
        purchaseRequestDO.setStatus(status);
        return purchaseRequestMapper.update(purchaseRequestDO) > 0;
    }

    /**
     * @Author: WangKe
     * @Description: 采购入库手动结单时更新采购申请状态
     * @Date: 2018/6/4 0004
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByManulFinish(PurchaseInboundDO inboundDO, String materialNo, String orgId) throws Exception {
        if (inboundDO == null) {
            return false;
        }
        List<PurchaseInboundDetailDO> inboundDetailDOList = purchaseInboundDetailMapper.findByOrder(inboundDO.getPurchaseInboundOrder(), orgId);
        if (ListUtil.isNullOrEmpty(inboundDetailDOList)) {
            return false;
        }

        PurchaseRequestVO requestVO = new PurchaseRequestVO();
        requestVO.setBillNo(inboundDO.getPurchaseRequestOrder());
        requestVO.setPurchaseOrgId(orgId);
        List<PurchaseRequestDO> requestDOList = purchaseRequestMapper.list(requestVO);
        if (ListUtil.isNullOrEmpty(requestDOList)) {
            return false;
        }
        PurchaseRequestDO requestDO = requestDOList.get(0);
        List<PurchaseRequestDetailDO> requestDetailDOList = purchaseRequestDetailMapper.list(requestDO.getBillId());
        if (ListUtil.isNullOrEmpty(requestDetailDOList)) {
            return false;
        }

        boolean success;
        BigDecimal sub;
        for (PurchaseRequestDetailDO requestDetailDO : requestDetailDOList) {
            if (!StringUtil.isNullOrEmpty(materialNo) && !materialNo.equals(requestDetailDO.getMaterialsNo())) {
                continue;
            }
            for (PurchaseInboundDetailDO inboundDetailDO : inboundDetailDOList) {
                if (requestDetailDO.getMaterialsNo().equals(inboundDetailDO.getMaterialNo())) {
                    if (inboundDetailDO.getStatus() != 2 && inboundDetailDO.getStatus() != 3) {
                        sub = inboundDetailDO.getAmount().subtract(inboundDetailDO.getRealAmount());
                        requestDetailDO.setSendQty(requestDetailDO.getSendQty().subtract(sub));

                        success = purchaseRequestDetailMapper.update(requestDetailDO) > 0;
                        if (!success) {
                            throw new Exception("更新采购申请详情失败");
                        }

                        //更新其他采购入库单的已入库意向数量
                        success = purchaseInboundDetailMapper.updateSendQty(orgId, requestDetailDO.getSendQty(),
                                requestDO.getBillNo(), requestDetailDO.getMaterialsNo()) > 0;
                        if (!success) {
                            throw new Exception("更新采购申请详情失败");
                        }
                    }
                }
            }
        }

        PurchaseRequestDO temp = new PurchaseRequestDO();
        temp.setBillId(requestDO.getBillId());
        temp.setInboundEnable(1);
        return purchaseRequestMapper.update(temp) > 0;
    }

    /**
     * 生成销售单后更改采购单状态
     *
     * @param purchaseRequestDO
     * @return
     * @throws Exception
     */
    public ErrorCode updateBySaleBill(PurchaseRequestDO purchaseRequestDO) {

        purchaseRequestMapper.updateBySaleBill(purchaseRequestDO);

        return ErrorCode.Success;
    }

    /**
     * @Author: WangKe
     * @Description: 更新采购申请是否可新增入库单
     * @Date: 2018/6/6 0006
     */
    public boolean updateInboundEnable(String billNo, String orgId) {
        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByPurchase(billNo, orgId);
        if (purchaseRequestDO == null) {
            return false;
        }
        List<PurchaseRequestDetailDO> requestDetailDOList = purchaseRequestDetailMapper.list(purchaseRequestDO.getBillId());
        if (ListUtil.isNullOrEmpty(requestDetailDOList)) {
            return false;
        }
        Integer enable = 2;
        for (PurchaseRequestDetailDO detailDO : requestDetailDOList) {
            if (detailDO.getQty().compareTo(detailDO.getSendQty()) > 0) {
                enable = 1;
                break;
            }
        }
        PurchaseRequestDO temp = new PurchaseRequestDO();
        temp.setBillId(purchaseRequestDO.getBillId());
        temp.setInboundEnable(enable);
        return purchaseRequestMapper.update(temp) > 0;
    }

    public List<PurchaseRequestDO> addressList(PurchaseRequestVO purchaseRequestVO) {
        List<PurchaseRequestDO> list = purchaseRequestMapper.addressList(purchaseRequestVO);
        return list;
    }

    public List<PurchaseGroupDO> purchaseGroupList(SearchCommonVO<PurchaseGroupDO> condition) {
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        return purchaseGroupMapper.list(condition.getFilters());
    }

//    /**
//     * @Author: WangKe
//     * @Description: 调用采购凭证创建接口
//     * @Date: 2018/8/1 0001
//     */
//    public ErrorCode sapPost(String id, String orgId) throws Exception {
//        PurchaseRequestDO requestDO = purchaseRequestMapper.item(id);
//        if (requestDO == null) {
//            throw new Exception("参数错误");
//        }
//        if (!"2".equals(requestDO.getBillStatus())) {
//            throw new Exception("采购单尚未审核通过，无法同步SAP");
//        }
//        if (requestDO.getSapStatus() != null && requestDO.getSapStatus() == 1) {
//            throw new Exception("采购单已经同步到SAP");
//        }
//
//        ImportParam importParam = fillImportParam(requestDO, orgId);
//        LogHelper.monitor("========调用采购凭证创建接口开始========");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========调用采购凭证创建接口结束========");
//        if (null == outputParam || outputParam.getCode() != 0) {
//            LogHelper.error("sap返回值为null", ErrorCode.RequestIdError.getCode());
//            throw new Exception("sap返回值为null");
//        }
//
//        PurchaseRequestDO temp = new PurchaseRequestDO();
//        temp.setBillId(id);
//        if ("OK".equals(outputParam.getDataHeader().get("RETURNCODE").toUpperCase())) {
//            if (StringUtil.isNullOrEmpty(outputParam.getDataHeader().get("EBELN"))) {
//                throw new Exception("采购凭证编号为null");
//            }
//            if (ListUtil.isNullOrEmpty(outputParam.getDataList())) {
//                throw new Exception("sap返回的零件详情列表为null");
//            }
//            temp.setSapStatus(1);
//            temp.setVoucherNo(outputParam.getDataHeader().get("EBELN"));
//            boolean success = purchaseRequestMapper.update(temp) > 0;
//            if (!success) {
//                throw new Exception("更新凭证编号失败");
//            }
//            List<Map<String, String>> dataList = outputParam.getDataList();
//            for (Map<String, String> map : dataList) {
//                String materialNo = map.get("MATNR").replaceAll("^(0+)", "");
//                LogHelper.monitor("===========BILL_NO: " + requestDO.getBillNo() + ", BILL_ID: " + id + ", MATERIAL_NO: " + materialNo + ", ROW_NO: " + Integer.valueOf(map.get("PO_ITEM")) + "===========");
//                purchaseRequestDetailMapper.updateRowNo(id, materialNo, Integer.valueOf(map.get("PO_ITEM")));
//                purchaseInboundDetailMapper.updateRowNo(requestDO.getBillNo(), Integer.valueOf(map.get("PO_ITEM")), materialNo, orgId);
//                purchaseInboundDetailMapper.updateBarcodeRowNo(requestDO.getBillNo(), Integer.valueOf(map.get("PO_ITEM")), materialNo, orgId);
//
//                purchaseInboundDetailMapper.updateInboundOrderRowNo(requestDO.getBillNo(), Integer.valueOf(map.get("PO_ITEM")), materialNo, orgId);
//                purchaseInboundDetailMapper.updateInboundRecordRowNo(requestDO.getBillNo(), Integer.valueOf(map.get("PO_ITEM")), materialNo, orgId);
//                // 回填净价
//                PurchaseRequestDetailDO detailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(id, materialNo, Integer.valueOf(map.get("PO_ITEM")));
//                if (detailDO != null) {
//                    BigDecimal totalNetPrice = (map.get("NETWR") == null ? BigDecimal.ZERO : new BigDecimal(map.get("NETWR")));
//                    detailDO.setNetPrice(totalNetPrice.divide(detailDO.getQty(), 2, BigDecimal.ROUND_HALF_UP));
//                    purchaseRequestDetailMapper.update(detailDO);
//                }
//            }
//        } else {
//            temp.setSapStatus(2);
//            temp.setSapErrorMsg(outputParam.getDataHeader().get("RETURNMSG"));
//            purchaseRequestMapper.update(temp);
//            throw new Exception(outputParam.getDataHeader().get("RETURNMSG"));
//        }
//        return ErrorCode.Success;
//    }
//
//    private ImportParam fillImportParam(PurchaseRequestDO requestDO, String orgId) throws Exception {
//        List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.list(requestDO.getBillId());
//        if (ListUtil.isNullOrEmpty(detailDOList)) {
//            throw new Exception("参数错误");
//        }
//        CompanyInfoVO companyInfoVO = companyInfoService.info(orgId);
//        if (companyInfoVO == null || companyInfoVO.getSapCode() == null) {
//            LogHelper.error("企业不存在,orgId:" + orgId, ErrorCode.RequestIdError.getCode());
//            throw new Exception("企业不存在");
//        }
//        CompanySupplierDO supplierDO = companySupplierMapper.itemBySupplierOrgId(orgId, requestDO.getSupplierOrgId());
//        if (supplierDO == null || StringUtil.isNullOrEmpty(supplierDO.getSupplierCode())) {
//            throw new Exception("供应商不存在");
//        }
//        CompanySupplierDO drawer = companySupplierMapper.itemBySupplierOrgId(orgId, requestDO.getDrawerOrgId());
//        if (drawer == null || StringUtil.isNullOrEmpty(drawer.getSupplierCode())) {
//            throw new Exception("出票方不存在");
//        }
//        String ordertype = "NB";
//        if (!StringUtil.isNullOrEmpty(requestDO.getPurchaseOrdType())) {
//            ordertype = requestDO.getPurchaseOrdType();
//        }
//        ImportParam importParam = new ImportParam();
//        // 2018.9.25由ZWJBJ_SET_ME21N调整为ZPMSBJ_SET_ME21N
//        importParam.setFunction("ZPMSBJ_SET_ME21N");
//        importParam.setTable("ZWJBJ_ME21N_ITEM");
//        Map<String, String> map = new HashMap<>();
//        map.put("BUKRS", companyInfoVO.getSapCode());
//        map.put("BSART", ordertype);
//        map.put("EKORG", companyInfoVO.getSapCode());
//        map.put("EKGRP", requestDO.getPurchaseGroup());
//        map.put("LIFNR", supplierDO.getSupplierCode());
//        map.put("BUSPARTNO", drawer.getSupplierCode());
//        importParam.setCommonParamMap(map);
//        Map<String, List<Map<String, String>>> tableParamMap = new HashMap<>();
//
//        List<Map<String, String>> dataList = new ArrayList<>();
//        Map<String, String> detailMap;
//        for (PurchaseRequestDetailDO detailDO : detailDOList) {
//            detailMap = new HashMap<>();
//            detailMap.put("MATNR", detailDO.getMaterialsNo());
//            detailMap.put("WERKS", companyInfoVO.getSapCode());
//            detailMap.put("MENGE", detailDO.getQty() + "");
//            detailMap.put("NETPR", detailDO.getNetPrice() + "");
//            detailMap.put("PEINH", "1");
//            detailMap.put("MEINS", detailDO.getUnit());
//            detailMap.put("PRSDR", "X");
//            detailMap.put("SCHPR", "");
//            detailMap.put("ZJHRQ", DateFormatUtils.format(detailDO.getDeliveryDate(), "yyyyMMdd"));
//            detailMap.put("LGORT", requestDO.getSapInArea());
//            dataList.add(detailMap);
//        }
//        tableParamMap.put("ZWJBJ_ME21N_ITEM", dataList);
//        importParam.setTableParamMap(tableParamMap);
//        importParam.setSapCode(companyInfoVO.getSapCode());
//        return importParam;
//    }

    public ErrorCode importAttach(String billId, MultipartFile file) throws Exception {
        PurchaseRequestDO requestDO = purchaseRequestMapper.item(billId);
        if (requestDO == null) {
            return ErrorCode.IllegalArument;
        }
        if ("2".equals(requestDO.getBillStatus())) {
            return ErrorCode.IllegalArument;
        }
        String fileName = billId + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        FileUtil.uploadFile(file, filePath + "purchase_request_attach/", fileName);
        PurchaseRequestDO temp = new PurchaseRequestDO();
        temp.setBillId(billId);
        temp.setAttachName(fileName);
        return purchaseRequestMapper.update(temp) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public void downloadAttach(String billId) throws Exception {
        PurchaseRequestDO requestDO = purchaseRequestMapper.item(billId);
        if (requestDO == null || StringUtil.isNullOrEmpty(requestDO.getAttachName())) {
            return;
        }
        FileUtil.downLoadFile(response, filePath + "purchase_request_attach/", requestDO.getAttachName());
    }

//    /**
//     * @Author: WangKe
//     * @Description: 读取采购订单接口
//     * @Date: 2018/8/29 0001
//     */
//    public List<String> sapAdd(String sapNo, String userId, String orgId) throws Exception {
//        if (StringUtil.isNullOrEmpty(sapNo)) {
//            throw new Exception("采购订单号为空");
//        }
//        PurchaseRequestDO request = purchaseRequestMapper.itemBySapBillNo(sapNo, orgId);
//        if (request != null) {
//            throw new Exception("此采购单号已生成订单，订单号为：" + request.getBillNo());
//        }
//        CompanyInfoVO companyInfoVO = companyInfoService.info(orgId);
//        if (companyInfoVO == null || companyInfoVO.getSapCode() == null) {
//            LogHelper.error("企业不存在,orgId:" + orgId, ErrorCode.RequestIdError.getCode());
//            throw new Exception("企业不存在");
//        }
//        if (null == companyInfoVO.getSapCode()) {
//            throw new Exception("企业SAP编码不存在");
//        }
//
//        ImportParam importParam = new ImportParam();
//        importParam.setFunction("ZPMS_GET_SGTUGINFO");
//        importParam.setTable("LT_COMPLIST2");
//        Map<String, String> headMap = new HashMap<>();
//        headMap.put("WERKS", companyInfoVO.getSapCode());
//        headMap.put("ZEBELN", sapNo);
//        importParam.setCommonParamMap(headMap);
//        importParam.setSapCode(companyInfoVO.getSapCode());
//        LogHelper.monitor("========调用读取采购订单接口开始========");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========调用读取采购订单接口结束========");
//        if (null == outputParam || outputParam.getCode() != 0) {
//            throw new Exception("调用sap接口失败");
//        }
//        if (ListUtil.isNullOrEmpty(outputParam.getDataList())) {
//            throw new Exception("sap返回值为空");
//        }
//        String errorMsg;
//        List<String> errorList = new ArrayList<>();
//        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
//        for (Map<String, String> map : outputParam.getDataList()) {
//            if (map.get("LOEKZ") != null && "X".equals(map.get("LOEKZ").toUpperCase())) {
//                errorMsg = "采购订单号：" + sapNo + "，行号：" + map.get("EBELP") + "，零件号：" + map.get("MATNR") + "，有删除标识";
//                errorList.add(errorMsg);
//                continue;
//            }
//            if (map.get("RETPO") != null && "X".equals(map.get("RETPO").toUpperCase())) {
//                errorMsg = "采购订单号：" + sapNo + "，行号：" + map.get("EBELP") + "，零件号：" + map.get("MATNR") + "，有退货标记";
//                errorList.add(errorMsg);
//                continue;
//            }
//
//            CompanySupplierDO supplierDO = companySupplierMapper.itemByCode(companyInfoVO.getOrgId(), map.get("LIFNR"));
//            if (supplierDO == null) {
//                errorMsg = "采购订单号：" + sapNo + "，供应商编码：" + map.get("LIFNR") + "，未找到此供应商";
//                errorList.add(errorMsg);
//                continue;
//            }
//            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(map.get("MATNR"), supplierDO.getIsPlatCompany() ? supplierDO.getOrgId() : orgId);
//            if (priMaterialsDO == null) {
//                errorMsg = "采购订单号：" + sapNo + "，行号：" + map.get("EBELP") + "，零件号：" + map.get("MATNR") + "，此零件不存在";
//                errorList.add(errorMsg);
//                continue;
//            }
//            PurchaseRequestDO requestDO = purchaseRequestMapper.itemBySapBillNo(sapNo, orgId);
//            if (requestDO == null) {
//                PurchaseRequestVO purchaseRequestVO = new PurchaseRequestVO();
//                purchaseRequestVO.setSeller(false);
//                purchaseRequestVO.setPurchaseOrgId(companyInfoVO.getOrgId());
//                purchaseRequestVO.setPurchaseOrgName(companyInfoVO.getCompanyName());
//                purchaseRequestVO.setSupplierOrgId(supplierDO.getSupplierOrgId());
//                purchaseRequestVO.setSupplierOrgName(supplierDO.getCompanyName());
//                purchaseRequestVO.setPurchaseGroup(map.get("EKGRP"));
//                purchaseRequestVO.setVoucherNo(map.get("EBELN"));
//                purchaseRequestVO.setSapStatus(1);
//                purchaseRequestVO.setCreateId(userId);
//                purchaseRequestVO.setCreateDate(new Date());
//                purchaseRequestVO.setSapBillNo(sapNo);
//                purchaseRequestVO.setBillStatus("2");
//                purchaseRequestVO.setPurchaseType("2");
//
//                List<PurchaseRequestDetailVO> list = new ArrayList<>();
//                PurchaseRequestDetailVO detailVO = new PurchaseRequestDetailVO();
//                detailVO.setMaterialsNo(priMaterialsDO.getMaterialsNo());
//                detailVO.setMaterialsDes(priMaterialsDO.getMaterialsDes());
//                detailVO.setUnit(priMaterialsDO.getUnit());
//                if (priMaterialsDO.getStandardPrice() != null) {
//                    detailVO.setPrice(priMaterialsDO.getStandardPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
//                } else {
//                    detailVO.setPrice(BigDecimal.ZERO);
//                }
//                detailVO.setSettlementPrice(detailVO.getPrice());
//                detailVO.setNetPrice(new BigDecimal(map.get("NETPR")));
//                detailVO.setQty(new BigDecimal(map.get("MENGE")));
//                detailVO.setRowNo(Integer.valueOf(map.get("EBELP")));
//                detailVO.setDeliveryDate(sdf.parse(map.get("EINDT")));
//                list.add(detailVO);
//                purchaseRequestVO.setMaterialsList(list);
//
//                this.insert(purchaseRequestVO, orgId, null, null);
//            } else {
//                PurchaseRequestDetailDO detailVO = new PurchaseRequestDetailDO();
//                detailVO.setBillId(requestDO.getBillId());
//                detailVO.setMaterialsNo(priMaterialsDO.getMaterialsNo());
//                detailVO.setMaterialsDes(priMaterialsDO.getMaterialsDes());
//                detailVO.setUnit(priMaterialsDO.getUnit());
//                detailVO.setNetPrice(new BigDecimal(map.get("NETPR")));
//                detailVO.setQty(new BigDecimal(map.get("MENGE")));
//                detailVO.setRowNo(Integer.valueOf(map.get("EBELP")));
//                detailVO.setDeliveryDate(sdf.parse(map.get("EINDT")));
//                if (priMaterialsDO.getStandardPrice() != null) {
//                    detailVO.setPrice(priMaterialsDO.getStandardPrice());
//                } else {
//                    detailVO.setPrice(BigDecimal.ZERO);
//                }
//                detailVO.setSettlementPrice(detailVO.getPrice());
//
//                BigDecimal amont = BigDecimal.valueOf(detailVO.getPrice().multiply(detailVO.getQty()).doubleValue());
//                detailVO.setApplyTotalPrice(amont);
//                purchaseRequestDetailMapper.insert(detailVO);
//
//                requestDO.setTotalValue(requestDO.getTotalValue().add(amont));
//                requestDO.setSettlementValue(requestDO.getTotalValue());
//                purchaseRequestMapper.update(requestDO);
//            }
//
//        }
//        return errorList;
//    }

    public List<PurchaseRequestDetailVO> getDetailByIds(List<String> ids) {
        List<PurchaseRequestDetailVO> list = new ArrayList<>();
        List<PurchaseRequestDetailDO> detailDOList = purchaseRequestDetailMapper.listByBIllIds(ids);
        if (ListUtil.isNullOrEmpty(detailDOList)) {
            return list;
        }
        for (PurchaseRequestDetailDO detailDO : detailDOList) {
            detailDO.setSettlementPrice(detailDO.getSettlementPrice().divide(new BigDecimal("100")));
            detailDO.setPrice(detailDO.getPrice().divide(new BigDecimal("100")));
            detailDO.setApplyTotalPrice(detailDO.getApplyTotalPrice().divide(new BigDecimal("100")));
            PurchaseRequestDetailVO purchaseRequestDetailVO = getDetailVO(detailDO);
            list.add(purchaseRequestDetailVO);
        }
        return list;
    }

    /**
     * 获取采购订单零件相关联数据（在途库存查询）
     *
     * @param condition
     * @return
     */
    public PageCommonVO listRequestMaterials(SearchCommonVO<PurchaseMaterialsShowVO> condition) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());

        PurchaseMaterialsShowVO showVO = condition.getFilters();

        if (StringUtils.isNotBlank(showVO.getBillNo())) {
            showVO.setBillNos(xcmg.device.infra.StringUtil.getStrSplitList(showVO.getBillNo()));
        }
        if (StringUtils.isNotBlank(showVO.getVoucherNo())) {
            showVO.setVoucherNos(xcmg.device.infra.StringUtil.getStrSplitList(showVO.getVoucherNo()));
        }
        if (null != showVO.getStartDate()) {
            showVO.setStartDate(DateUtil.getStartTimeOfDay(showVO.getStartDate()));
        }
        if (null != showVO.getEndDate()) {
            showVO.setEndDate(DateUtil.getEndTimeOfDay(showVO.getEndDate()));
        }

        showVO.setShowByDeliveryReceipt(showByDeliveryReceipt(showVO.getOrgId()) ? SHOW_BY_RECEIPT_YES : SHOW_BY_RECEIPT_NO);
        List<PurchaseMaterialsShowVO> materials = purchaseRequestDetailMapper.listRequestMaterials(showVO);
        pageCommonVO.setPageInfo(new PageInfo(materials));
        pageCommonVO.setPageInfoList(materials);
        return pageCommonVO;
    }

    /**
     * 根据配置判断该公司展示的报表数据是否根据发运交接单签收状态显示
     *
     * @param orgId
     * @return
     */
    private boolean showByDeliveryReceipt(String orgId) {
        List<SystemParameter> systemParameters = systemParameterService.listByParamType(SHOW_BY_DELIVERY_RECEIPT);
        if (CollectionUtils.isEmpty(systemParameters)) {
            return false;
        }
        for (SystemParameter parameter : systemParameters) {
            if (orgId.equals(parameter.getParamValue())) {
                return true;
            }
        }
        return false;
    }


    public void exportInventoryReport(PurchaseMaterialsShowVO condition) throws Exception {
        List<PurchaseMaterialsShowVO> resultVOList = new ArrayList<>();
        if (StringUtils.isNotBlank(condition.getBillNo())) {
            condition.setBillNos(xcmg.device.infra.StringUtil.getStrSplitList(condition.getBillNo()));
        }
        if (StringUtils.isNotBlank(condition.getVoucherNo())) {
            condition.setVoucherNos(xcmg.device.infra.StringUtil.getStrSplitList(condition.getVoucherNo()));
        }
        if (null != condition.getStartDate()) {
            condition.setStartDate(DateUtil.getStartTimeOfDay(condition.getStartDate()));
        }
        if (null != condition.getEndDate()) {
            condition.setEndDate(DateUtil.getEndTimeOfDay(condition.getEndDate()));
        }
        condition.setShowByDeliveryReceipt(showByDeliveryReceipt(condition.getOrgId()) ? SHOW_BY_RECEIPT_YES : SHOW_BY_RECEIPT_NO);
        Integer count = purchaseRequestDetailMapper.listRequestMaterialsCount(condition);

        int times = count / 1000 + 1;
        for (int i = 0; i < times; i++) {
            PageHelperPlus.startPage(i + 1, 1000);
            resultVOList.addAll(purchaseRequestDetailMapper.listRequestMaterials(condition));
        }
        String title = "在途库存报表数据导出";
        String[] rowsName = new String[]{"序号", "采购单号", "采购凭证号", "采购行号", "零件号",
                "零件名称", "下单数量", "未交货数量", "单位", "下单时间", "采购组", "制单人", "交货时间", "库区", "供应商编号", "供应商描述", "是否直投"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < resultVOList.size(); i++) {
            PurchaseMaterialsShowVO e = resultVOList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = e.getBillNo();
            objs[2] = e.getVoucherNo();
            objs[3] = e.getRowNo();
            objs[4] = e.getMaterialsNo();
            objs[5] = e.getMaterialsDes();
            objs[6] = e.getQty();
            objs[7] = e.getNoInboundQty();
            objs[8] = e.getUnit();
            objs[9] = DateUtil.formatDateTime(e.getCreateDate());
            objs[10] = e.getPurchaseGroup();
            objs[11] = e.getCreateName();
            objs[12] = DateUtil.formatDateTime(e.getDeliveryDate());
            objs[13] = e.getInArea();
            objs[14] = e.getSupplierSapCode();
            objs[15] = e.getSupplierOrgName();
            objs[16] = xcmg.device.infra.StringUtil.getTrueOrFalse(e.getIsDirectCast());
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    public ErrorCode createContract(String[] ids) {
        for (String id : ids) {
            PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.item(id);
            PurchaseRequestCrmDO purchaseRequestCrmDO = new PurchaseRequestCrmDO();
            purchaseRequestCrmDO.setPmsCode(purchaseRequestDO.getBillNo());
            purchaseRequestCrmDO.setAddress(purchaseRequestDO.getReceiverAddress());
            purchaseRequestCrmDO.setTel(purchaseRequestDO.getReceiverTel());
            purchaseRequestCrmDO.setRemarks(purchaseRequestDO.getRemark());
            List<PurchaseRequestDetailDO> purchaseRequestDetailDOList = purchaseRequestDetailMapper.list(id);
            CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(purchaseRequestDO.getSupplierOrgId(), purchaseRequestDO.getDeliveryOrgId());
            if (!ObjectUtils.isEmpty(companyDealerDO)) {
                purchaseRequestCrmDO.setContact(companyDealerDO.getDealerCode());
            }
            List<PurchaseRequestDetailCrmDO> lines = new ArrayList<>();
            for (PurchaseRequestDetailDO purchaseRequestDetailDO : purchaseRequestDetailDOList) {
                PurchaseRequestDetailCrmDO purchaseRequestDetailCrmDO = new PurchaseRequestDetailCrmDO();
                purchaseRequestDetailCrmDO.setMaterialsNo(purchaseRequestDetailDO.getMaterialsNo());
                purchaseRequestDetailCrmDO.setPrice(purchaseRequestDetailDO.getPrice().divide(new BigDecimal(1000000), 6, RoundingMode.HALF_UP).toString());
                purchaseRequestDetailCrmDO.setPurchaseQty(purchaseRequestDetailDO.getQty().toString());
                lines.add(purchaseRequestDetailCrmDO);
            }
            purchaseRequestCrmDO.setLine(lines);

//            logger.info("采购申请同步crm生成采购信息,接口入参{}", JsonUtil.objectToString(purchaseRequestCrmDO));
//            Map resultMap = crmClient.createContract(purchaseRequestCrmDO);
//            logger.info("采购申请同步crm生成采购信息,返回结果{}", JsonUtil.objectToString(resultMap));
//
//            if (resultMap.get("Flag").equals(true)) {
//                purchaseRequestDO.setSyncCrmFlag("1");
//            } else {
            purchaseRequestDO.setSyncCrmFlag("2");
//            }
//            purchaseRequestDO.setSyncCrmMsg(resultMap.get("Msg").toString());
            purchaseRequestMapper.update(purchaseRequestDO);
        }
        return ErrorCode.Success;
    }

    public List<String> selectIdForCrm(String orgId) {
        return purchaseRequestMapper.selectIdForCrm(orgId);
    }


    /**
     * @Desc 采购订单-供货及时性
     * @Author Mr.dong
     * @Date 2021/6/8 10:40
     */
    public PageCommonVO timelinessReport(SearchCommonVO<TimelinessReportParamVO> condition) {

        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        TimelinessReportParamVO filters = condition.getFilters();
        List<TimelinessReportVO> reportVOList = purchaseRequestMapper.timelinessReport(filters);
        PageCommonVO result = new PageCommonVO();
        result.setPageInfo(new PageInfo(reportVOList));
        result.setPageInfoList(reportVOList);
        return result;
    }


    /**
     * @Desc 采购订单-供货及时性导出
     * @Author Mr.dong
     * @Date 2021/6/8 10:40
     */
    public void exportTimelinessReport(TimelinessReportParamVO condition) throws Exception {

        List<TimelinessReportVO> reportVOList = purchaseRequestMapper.timelinessReport(condition);
        processExport(reportVOList);
    }

    /**
     * @Desc 处理导出
     * @Author Mr.dong
     * @Date 2021/6/9 16:48
     */
    private void processExport(List<TimelinessReportVO> reportVOList) throws Exception {
        if (CollectionUtils.isEmpty(reportVOList)) {
            throw new Exception("导出数据不能为空");
        }
        //自动内存分页，每页一万条
        List<List<TimelinessReportVO>> partList = Lists.partition(reportVOList, 10000);

        String fileName = "采购订单供货及时性数据";
        EasyExcelUtil.prepareResponse(response, fileName);

        //批量数据导出
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), TimelinessReportVO.class).build();
        WriteSheet writeSheet;
        for (int i = 0; i < partList.size(); i++) {
            writeSheet = EasyExcel.writerSheet("数据" + (i + 1)).build();
            excelWriter.write(partList.get(i), writeSheet);
        }
        excelWriter.finish();//关闭流
    }

    public void setPullRecord() throws Exception {
        TaskRecordDO taskRecordDO = new TaskRecordDO();
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            throw new Exception("生成ID失败");
        }
        taskRecordDO.setId(textResult.getValue());
        taskRecordDO.setType(String.valueOf(TaskRecordEnum.PULL_PURCHASE_STOCK.getCode()));
        taskRecordDO.setTypeName(TaskRecordEnum.PULL_PURCHASE_STOCK.getDesc());
        taskRecordDO.setTime(new Date());
        taskRecordMapper.insert(taskRecordDO);
    }

//    public void pullStockInfo() throws Exception {
//        int count = purchaseRequestMapper.selectUnStockCount(companyUtil.ynOrgId());
//        if (count > 0) {
//            int page = count / 10;
//            int lastNum = count % 10;
//            if (lastNum > 0) {
//                page = page + 1;
//            }
//            for (int i = page; i > 0; i--) {
//                int startNum = 0;
//                int endNum = 0;
//                if (i == page) {
//                    startNum = (i - 1) * 10;
//                    endNum = count;
//                    List<String> billNos = purchaseRequestMapper.listUnStockInfos(companyUtil.ynOrgId(), startNum, endNum);
//                    convertInfo(billNos);
//                } else {
//                    startNum = (i - 1) * 10;
//                    endNum = i * 10;
//                    List<String> billNos = purchaseRequestMapper.listUnStockInfos(companyUtil.ynOrgId(), startNum, endNum);
//                    convertInfo(billNos);
//                }
//            }
//        }
//    }

//    private void convertInfo(List<String> billNos) throws Exception {
//        for (String billNo : billNos) {
//            ActionResult result = erpSyncClient.checkStock(billNo);
//            if (ErrorCode.Success.getCode() == result.getCode()) {
//                List<StockVO> stockVOs = (List<StockVO>) result.getValue();
//                if (CollectionUtils.isNotEmpty(stockVOs)) {
//                    for (StockVO stockVO : stockVOs) {
//                        BillStockDO billStockDO = new BillStockDO();
//
//                        ActionResult<String> textResult = fastGenClient.textGuid();
//                        if (textResult.getCode() != ErrorCode.Success.getCode()) {
//                            throw new Exception("生成ID失败");
//                        }
//
//                        billStockDO.setId(textResult.getValue());
//                        billStockDO.setBillNo(stockVO.getGysddcode());
//                        billStockDO.setMaterialCode(stockVO.getMaterialcode());
//                        billStockDO.setQuantity(stockVO.getRecquantity());
//                        purchaseRequestMapper.mergeIntoStockInfo(billStockDO);
//                    }
//                }
//            }
//        }
//    }

}
